有人知道AFNetworking的呼叫是否会自动发送到后台线程吗?
例如,这就是我所拥有的......
ServerAccessLayer.m
- (void)fetchWithurlString:(NSString *)urlString andCompletion:(APIResponseObjectBlock)completion
{
[[WebClient sharedClient] fetchDictionaryWithURLString:urlString success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(YES, responseObject, operation.response.statusCode, nil, nil);
});
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error, NSInteger statusCode, id responseObject) {
if (completion) {
NSArray *messages = [self generateResponseArray:responseObject withDataType:MESSAGE];
NSArray *errors = [self generateResponseArray:responseObject withDataType:ERROR];
dispatch_async(dispatch_get_main_queue(), ^{
completion(NO, responseObject, statusCode, messages, errors);
});
}
}];
}
WebClient.m
- (void)fetchDictionaryWithURLString:(NSString *)urlString success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *, NSInteger, id))failure
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
success(operation, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(operation, error, ((NSHTTPURLResponse *)operation.response).statusCode, operation.responseObject);
}];
}
在ServerAccessLayer中,我在主线程上重新发送完成代码。我很久以前编写这段代码时,我的假设是因为当使用AFHTTPRequestOperationManager时,它会自动在后台线程上调度,所以我没有实现它。现在,我似乎无法找到任何证据,而且我想知道我是否实际上没有在后台线程上调用任何网络电话。
如果AFHTTPRequestOperationManager自动在后台线程上工作,有人可以验证我,还是我需要自己处理?
答案 0 :(得分:3)
AFNetwork是开源的,因此您可以在Github上实际查看所有代码:https://github.com/AFNetworking/AFNetworking
查看AFHTTPRequestOperationManager
,您可以看到它在初始化时创建了自己的操作队列。所有网络请求都发生在此操作队列中。然后,默认情况下,将完成和失败块分派回主队列。
简而言之,您的网络操作将在后台进行,但您的success
和failure
块将位于主队列中。