Passing blocks to a AFNetworking method?

半腔热情 提交于 2019-12-03 15:34:19

Factorize the API call to something like

+ (void)getDataFromServerWithParameters:(NSMutableDictionary *)params completion:(void (^)(id JSON))completion failure:(void (^)(NSError * error))failure {
     NSString * path = @"resources/123";
     NSMutableURLRequest *request = [self.httpClient requestWithMethod:@"POST" path:path parameters:params];
     AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        if (completion)
            completion(JSON);
     } failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON) {
        if (failure)
            failure(error);
     }];

     [httpClient enqueueHTTPRequestOperation:operation];
 }

You can place this method in a utility class like XYAPI and just invoke it from your controllers like

 [XYAPI getDataFromServer:params completion:^(id JSON){
     // do something, for instance reload the table with a new data source
     _myArray = JSON;
     [_myTableView reloadData];
 } failure:^(NSError * error) {
    // do something
 }];

Also you don't need to spawn a new AFHTTPClient at every request. Configure and use a shared one in the XYAPI class. Something like

+ (AFHTTPClient *)httpClient {
    static AFHTTPClient * client = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://foo.com/api/v1/"]];
        [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
    });
    return client;
}

Note that this implementation is already used in the above example.
self in the context of a class method is the class itself, so self.httpClient is indeed resolved at runtime as [XYAPI httpClient].

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!