KVISH
KVISH

Reputation: 13178

AFNetworking happening on the main thread

I have a question with AFNetworking. I read the documentation here:

http://afnetworking.github.com/AFNetworking/Classes/AFImageRequestOperation.html

It says:

urlRequest: The request object to be loaded asynchronously during execution of the operation.

Problem is when I execute the request for below, its happening on the main thread. I was able to confirm it by checking if it's in the main thread or not:

AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:urlrequest success:^(UIImage *image) {
    if ([NSThread mainThread]){
        NSLog(@"this is the main thread");
    }
}];
[operation start];

Is there anything I am doing incorrectly? Was I interpreting the documentation wrong? Why is it not asynchronous following the documentation?

Upvotes: 3

Views: 6651

Answers (3)

Diwann
Diwann

Reputation: 906

KVISH > However, you can assign a different successCallbackQueue :

dispatch_queue_t backgroundQueue = dispatch_queue_create("com.name.bgqueue", NULL);
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.successCallbackQueue = backgroundQueue;

Upvotes: 13

EarlyRiser
EarlyRiser

Reputation: 736

The image is being loaded in the background and then your success block is being called on the main thread.

The point of this is that the loading of the image which takes some time and would block your UI is done on the background, but once the image is loaded you probably want to do something like set it on a UIImageView and that requires being on the main thread.

Upvotes: 11

KVISH
KVISH

Reputation: 13178

Wow, can't believe I didn't notice this myself before asking. In the AFNetworking classes, it has the below:

dispatch_async(requestOperation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) {
                    success(operation.request, operation.response, processedImage);
                });

So the success is called on the main queue. Case closed.

Upvotes: 1

Related Questions