2

I put a NSMutableURLRequest request in dispatch_async but it doesn't work. However, NSURLRequest works. Code:

dispatch_queue_t queue1 = dispatch_get_global_queue(0, 0);
dispatch_async(queue1, ^{

    NSMutableURLRequest* request  = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
    [request setHTTPMethod:@"GET"];
    NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil];
    [connection start];//It doesn't work!

    //***
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
    NSURLResponse* theResponse = nil;
    NSError* theError = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:theRequest
                                         returningResponse:&theResponse 
                                                     error:&theError];
    //This works great!
});

Is there any difference between NSMutableURLRequest and NSURLRequest? Or, I use the NSURLConnection in a wrong way?

Thanks!

fannheyward
  • 18,599
  • 12
  • 71
  • 109

1 Answers1

2

It's not that you're using a mutable connection in one place and not the other, it's that you're calling the synchronous request method which runs immediately on the current thread versus an asynchronous method which needs a run loop to operate. From the documentation for -[NSURLConnection start]:

If you don’t schedule the connection in a run loop or an operation queue before calling this method, the connection is scheduled in the current run loop in the default mode.

Calling the asynchronous method from a block on a background thread is redundant. You should either call the async method on the main thread (it returns immediately and schedules its work in the background) or call the synchronous method in the async dispatched block. Doing it the second way, you don't have to deal with all the delegate callbacks, but you give up some control over the load operation.

davehayden
  • 3,484
  • 21
  • 28