2013-06-20 28 views
46

AFNetworking是否调用主线程上的完成块?或者它是否在后台调用,需要我手动将UI更新发送到主线程?在主线程上调用AFNetworking成功/失败块吗?

使用代码来代替的话,这是从AFNetworking documentation与调用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]; 
+0

@tdarr所有的源代码都可用,看看,你可以知道这一切 – onmyway133

回答

24

在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属性已被移动到AFURLSessionManager(其AFHTTPSessionManager延伸)。

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

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

这应该被接受的答案! – XeNoN

+0

我同意!我编辑了包含AFNetworking 3的答案,并添加了两个版本的源代码链接。 – thomasd

+0

@ thomasd谢谢。你的编辑有一些拒绝,所以我不能接受它,但我只是复制它。 – onmyway133

41

调用它们的主队列,除非你明确地设定了AFHTTPRequestOperation队列,如图setCompletionBlockWithSuccess:failureAFHTTPRequestOperation.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); 
      }); 
     } 
    } 
}; 
+0

谢谢!我想我可以读的来源... – thomasd

+0

不知道大概应该已经检查,而不是假设他们只是执行他们在同一线程作为请求 –

5

正如每个人解释,这是在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];