将 API 调用分解为类似的内容
+ (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];
}
您可以将此方法放在实用程序类中,例如XYAPI
然后从你的控制器调用它,比如
[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
}];
而且你不需要产生一个新的AFHTTPClient
应每一个要求。配置并使用共享的XYAPI
班级。就像是
+ (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;
}
请注意,上面的示例中已经使用了此实现。
self
在类方法的上下文中是类本身,所以self.httpClient
确实在运行时解析为[XYAPI httpClient]
.