是否在主线程上调用了AFNetworking成功/失败块?

时间:2013-06-20 22:56:38

标签: ios afnetworking

AFNetworking是否在主线程上调用完成块?或者是在后台调用,要求我手动将我的UI更新分发给主线程?

使用代码而不是单词,这是来自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];

4 个答案:

答案 0 :(得分:42)

除非您在AFHTTPRequestOperation上明确设置队列,否则会在主队列上调用它们,如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);
            });
        }
    }
};

答案 1 :(得分:31)

在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;

答案 2 :(得分: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];

答案 3 :(得分:1)

您可以通过指定completionGroup,completionQueue see the AFNetworking API document

来设置完成回调队列