我有以下运行良好的代码,但我需要对其进行更多控制,尤其是需要开始使用0.9中的Reachability代码。
NSString *urlString = [NSString stringWithFormat:@"http://example.com/API/api.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
_self.mainDictionary = [JSON valueForKeyPath:@"elements"];
[_self parseLiveData];
} failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON){
//NSLog(@"Failed: %@",[error localizedDescription]);
}];
if (operation !=nil && ([self.sharedQueue operationCount] == 0)) {
[self.sharedQueue addOperation:operation];
}
我正在努力研究如何将相同的代码转换为使用AFHTTPClient的方式,以便可以利用“setReachabilityStatusChangeBlock”的优势。
最佳答案
只需创建一个具有单例的AFHTTPClient的子类
+ (id)sharedHTTPClient
{
static dispatch_once_t pred = 0;
__strong static id __httpClient = nil;
dispatch_once(&pred, ^{
__httpClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"http://example.com/API"]];
[__httpClient setParameterEncoding:AFJSONParameterEncoding];
[__httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
});
return __httpClient;
}
然后调用getPath方法
[[YourHTTPClient sharedHTTPClient]
getPath:@"api.php"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id JSON){
_self.mainDictionary = [JSON valueForKeyPath:@"elements"];
[_self parseLiveData];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//NSLog(@"Failed: %@",[error localizedDescription]);
}];
关于iphone - AFNetworking(AFJSONRequestOperation)转换为AFHTTPClient,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9411364/