Reputation: 103
I got a problem with NSURLConnection and spent more than 3 days to find a solution but unfortunately, i haven't get one. Here is my code, this is in a dedicated class and use completehandler to return
NSURL *myUrl = [NSURL URLWithString:targetSite];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:myUrl
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:timeOutInterval];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:MYBODYCONTENT];
conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if(conn)
{
webData = [NSMutableData data];
}
and use delegate to receive data, it works fine in "didReceiveResponse", "didReceiveData", "didFailWithError", "connectionDidFinishLoading", ...
BUT, if a request timeout happend, (i already did [conn cancel] in "didFailWithError")
then, in a peroid of time (I didn't do a precise count but about 1 min)
All my new request to the same server(request again) will be timeout again and again.
Is there anything I do wrong?
Or anything I should modify my code?
I have tried lots of solutions but still no go.
So, looking for some help, thanks.
Upvotes: 2
Views: 246
Reputation: 437381
One common problem is that if you initiate many NSURLConnection
requests, it can only run a certain number concurrently (usually 4 or 5). So, if you initiate more than that, it can only run a few of them at a time, and all the others will get backlogged, waiting until one of the slots becomes available. Sadly, if this takes more than a minute, the latter requests can timeout.
One solution to this is to wrap your NSURLConnection
objects in custom NSOperation
subclass. Then rather than just starting the connections all at once, you can add them to a NSOperationQueue
, letting the operation queue decide when to start them. So, if you define that queue's maxConcurrentOperationCount
to be 4 or 5, then the operation queue will not try to start them all at the same time, solving the NSURLConnection
timeout problem.
For background regarding how to subclass NSOperation
for concurrent operation, see Configuring Operations for Concurrent Execution section of the Concurrency Programming Guide: Operation Queues. See https://stackoverflow.com/a/24943851/1271826 for a demonstration of wrapping NSURLConnection
objects in NSOperation
subclass.
Even better, if you don't want to get lost in the details here, consider using AFNetworking, which uses an operation queue solution (for AFHTTPRequestOperationManager
, at least). Just make sure to set the manager's operation queue's maxConcurrentOperationCount
to, say 4, and then one can add as many network operations as desired, and the operation queue will ensure they won't timeout.
Upvotes: 1