49

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];
4

4 回答 4

43

它们在主队列上调用,除非您明确将队列设置为 on 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);
            });
        }
    }
};
于 2013-06-20T23:03:08.273 回答
32

在 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;
于 2014-07-02T08:36:23.077 回答
6

正如大家所解释的,它在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];
于 2015-07-21T13:13:46.190 回答
1

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

于 2013-12-20T06:36:45.673 回答