iphonensconnection

How to set real timeout for NSURLConnection request?


Please look to the following code:

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:<...> cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:3.0]; 
<...>
[NSURLConnection sendSynchronousRequest:request returningResponse:&WSresponse error:&WSerror]

This code bellow is called from a background thread:

[self performSelectorInBackground:@selector(<...>) withObject:nil];

Sometimes sendSynchronousRequest works much more than 3.0 sec. (abount 1 minute).

  1. How to set real timeout instead not working timeoutInterval:3.0?
  2. How to add an ability to user to stop freezing NSURLConnection request by Cancel button in any moment?

Thanks a lot for help!


Solution

    1. Note that in addition to the initializer you called, you can also call -setTimoutInterval: on an NSMutableURLRequest. The timeout value does indeed work, but any value less than 240 is ignored -- that's the minimum value respected by the iOS framework. If you want to set a lower timeout value, then your only choice is to use an asynchronous request.

    2. If you want to asynchronously cancel a request (ie, perform the request in the background and allow the foreground UI thread to issue a cancel in response to the user hitting a Cancel or Stop button), then you have to make an asynchronous URL request. There's no way to do it with a synchronous request. For example, you can't even kill a dispatch queue while it is currently executing a block.

    You might want to look at ASIHTTPRequest, which wraps up some of this functionality a bit differently.