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

tho*_*asd 47 ios 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];
Run Code Online (Sandbox Code Playgroud)

应该这样写吗?

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];
Run Code Online (Sandbox Code Playgroud)

Mar*_*bri 42

它们在主队列上调用,除非你明确地设置了队列AFHTTPRequestOperation,如setCompletionBlockWithSuccess:failurefrom 所示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);
            });
        }
    }
};
Run Code Online (Sandbox Code Playgroud)


onm*_*133 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
Run Code Online (Sandbox Code Playgroud)

在AFNetworking 3中,该completionQueue属性已移至AFURLSessionManager(AFHTTPSessionManager扩展).

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

@property (nonatomic, strong) dispatch_queue_t completionQueue;
@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;
Run Code Online (Sandbox Code Playgroud)


Oha*_*adM 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];
Run Code Online (Sandbox Code Playgroud)

AFNetworking 3.xx:

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
[self setCompletionQueue:myQueue];
Run Code Online (Sandbox Code Playgroud)