GCD and async NSURLConnection

前端 未结 4 1884
刺人心
刺人心 2020-12-04 17:03

I know that if I create an NSURLConnection (standard async one), it will call back on the same thread. Currently this is on my main thread. (work fine too).

But i\'m

4条回答
  •  天命终不由人
    2020-12-04 17:31

    First off, your block and every variable you use within it will get copied to GCD, so the code will not be executed on your thread but on the global queue.

    If you want to get your data back on the main thread, you can nest an async call after your data has been fetched:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"www.stackoverflow.com"]];
        NSURLResponse *response;
        NSError *error;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        if (error) {
            // handle error
            return;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            // do something with the data
        });
    });
    

    But why not use NSURLConnection's built in asynchronous support? You need an NSOperationQueue, but if you are doing alot of network fetches it is the way to go anyway:

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"www.stackoverflow.com"]];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:self.queue // created at class init
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
                               // do something with data or handle error
                           }];
    

    Personally, I use a library like AFNetworking or ASIHTTPRequest to make networking even easier, which both support blocks (the former utilizes GCD and is a bit more modern).

提交回复
热议问题