AFNetworking 3.0.4更新使用

最近更新了AFNetworking的版本,用了最新的3.0.4json

發現較以前使用的2.5版本有較大的區別session

在文件目錄結構上3.0.4去除了NSURLConnection這個文件夾和裏面的url

AFHTTPRequestOperation.hspa

AFHTTPRequestOperation.mcode

AFHTTPRequestOperationManager.horm

AFHTTPRequestOperationManager.m隊列

AFURLConnectionOperation.hip

AFURLConnectionOperation.mstring

這6個文件it


在以前的2.5版本中咱們常使用的方法是:

    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
                        
    NSDictionary *params = @{ @"PPID":[NSString stringWithFormat:@"%ld", (long)ppId],
                              @"UserID":userId,
                            };
    
    [mgr POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        if (isSuccessRsp(jsonRsp))
        {
            success(jsonRsp);
        }
        else
        {
            failure(errorMsgRsp(jsonRsp));
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failure(error.description);
    }];


- (AFHTTPRequestOperation *)POST:(NSString *)URLString
                  headParameters:(id)headParameters
                  bodyParameters:(id)bodyParameters
                         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    [self setHeadParameters:headParameters];
    
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString] absoluteString] parameters:bodyParameters error:nil];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    
    [self.operationQueue addOperation:operation];
    
    return operation;
}

同時也不須要手動寫隊列


現3.0.4使用方法更加簡單

- (void)POST:(NSString *)URLString
           headParameters:(id)headParameters
           bodyParameters:(id)bodyParameters
                  success:(void (^)( id responseObject))success
                  failure:(void (^)( NSError *error))failure
{
    NSURL *url= [NSURL URLWithString:URLString];
    if (url == NULL)
    {
        return;
    }
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    
    if (headParameters)
    {
        [self setHeadParameters:headParameters sessionMgr:sessionManager];
    }

    [sessionManager POST:[url absoluteString] parameters:bodyParameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}
相關文章
相關標籤/搜索