在主线程上调用AFNetworking成功/失败块吗?

AFNetworking是否调用主线程上的完成块? 或者是在后台调用,需要我手动调度我的UI更新到主线程?

使用代码而不是单词,这是来自AFNetworking文档的示例代码,调用NSLog取代了UI更新:

 AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { self.label.text = JSON[@"text"]; } failure:nil]; 

应该这样写吗?

 AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { dispatch_async(dispatch_get_main_queue(), ^{ self.label.text = JSON[@"text"]; }); } failure:nil]; 

在AFNetworking 2中, AFHTTPRequestOperationManager有一个completionQueue属性。

请求操作的completionBlock的调度队列。 如果为NULL (默认),则使用主队列。

  #if OS_OBJECT_USE_OBJC @property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; #else @property (nonatomic, assign, nullable) dispatch_queue_t completionQueue; #endif 

在AFNetworking 3中, completionQueue属性已被移至AFURLSessionManagerAFHTTPSessionManager扩展)。

completionBlock的调度队列。 如果为NULL (默认),则使用主队列。

 @property (nonatomic, strong) dispatch_queue_t completionQueue; @property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; 

它们在主队列上被调用,除非你AFHTTPRequestOperationsetCompletionBlockWithSuccess:failure上设置队列,如setCompletionBlockWithSuccess:failure AFHTTPRequestOperation.m

 self.completionBlock = ^{ if (self.error) { if (failure) { dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ failure(self, self.error); }); } } else { if (success) { dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ success(self, self.responseData); }); } } }; 

正如大家所解释的那样,它是在AFNetworking的源代码中,至于如何做到这一点,

AFNetworking 2.xx:

 // Create dispatch_queue_t with your name and DISPATCH_QUEUE_SERIAL as for the flag dispatch_queue_t myQueue = dispatch_queue_create("com.CompanyName.AppName.methodTest", DISPATCH_QUEUE_SERIAL); // init AFHTTPRequestOperation of AFNetworking operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; // Set the FMDB property to run off the main thread [operation setCompletionQueue:myQueue]; 

AFNetworking 3.xx :

 AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init]; [self setCompletionQueue:myQueue]; 

您可以通过指定completionGroup来设置完成callback队列,completionQueue 参见AFNetworking API文档