Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit to number of simultaneous NSURLConnection Requests in iOS 5?

Tags:

http

ios

cocoa

In iOS 5 only, an application I'm working on seems to drop requests when I send a large number of requests asynchronously. Large meaning still fairly small - testing with 30 right now

Each request uses it's own NSURLConnection and is expected to return relatively quickly ( ie. 300 ms - 2s ). We also keep one connection open for a long period of time.

It seems like every 5th connection fails to leave the device. It certainly never reaches the server, and network debugging using Charles doesn't even show the requests going out.

I'm wondering if anyone knows of a limit to the number of simultaneous open NSURLConnection objects and active requests?

It's worth noting that we do not see this issue in iOS 4. It also seems that if we kill our long-lived connection, then we don't drop every 5th request any more.

like image 464
wallacer Avatar asked Oct 07 '22 15:10

wallacer


1 Answers

NSOperationQueue is the best way to manage this problem. In a nutshell, you wrap your NSURLConnection in an NSBlockOperation, then add it to the queue. The queue allows you to set various properties such as the maximum number of simultaneous connections, and also give you an easy way to cancel queued operations.

There is a good intro to this design pattern in a WWDC video (2012) called "Building Concurrent User Interfaces on iOS".

In iOS 5 you can use the following call to start an NSURLConnection and add it to an NSOperationQueue

+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler

like image 122
Sam Clewlow Avatar answered Oct 10 '22 12:10

Sam Clewlow