I’m creating an app which communicates alot with a server. I want to make sure I have only 1 connection at a time – only 1 request pending. I want so that if I try to send another request, It will wait until the current one is finished before sending the next.
How can I implement This?
Tnx!
I don’t know of any automatic mechanism to do this. So you have to write a new class yourself (let’s call it
ConnectionQueue):Basically, instead of a creating the
NSURLConnectiondirectly, you call a method of yourConnectionQueueclass (which should have exactly one instance) taking theNSURLRequestand the delegate as a parameter. Both are added to a queue, i.e. a separateNSArrayfor the requests and the delegates.If the arrays contains just one element, then no request is outstanding and you can create a
NSURLConnectionwith the specified request. However, instead of the delegate passed to the method, you pass yourConnectionQueueinstance as the delegate. As a result, the connection queue will be informed about all actions of the connection. In most cases, you just forward the callback to the original delegate (you’ll find it in the first element of the delegate array).However, if the outstanding connection completes (
connection:didFailWithError:orconnectionDidFinishLoading:is called), you first call the original delegate and then remove the connection from the two arrays. Finally, if the arrays aren’t empty, you start the next connection.Update:
Here’s some code. It compiles but hasn’t been tested otherwise. Furthermore, the implementation of the
NSURLConnectionDelegateprotocol is incomplete. If you’re expecting more than implemented callbacks, you’ll have to add them.Header File:
Implementation:
To use the connection queue, create an NSURLRequest instance and then call:
There’s no need to create the singleton instance of
ConnectionQueueexplicitly. It will be created automatically. However, to properly clean up, you should call[ConnectionQueue releaseShared]when the application quits, e.g. fromapplicationWillTerminate:of your application delegate.