I am interacting with a web-controlled hardware device. You send it a request via a URL (e.g., http://device/on?port=1 or http://device/off?port=3) to turn stuff on and off, and it sends back “success” or “failure”. It is a simple device, however, so while it’s processing a request — i.e., until it returns the status of the request that it’s processing — it will ignore all subsequent requests. It does not queue them up; they just get lost.
So I need to send serial, synchronous requests. I.e., req#1, wait for response#1, req#2, wait for response#2, req#3, wait for response #3, etc.
Do I need to manage my own thread-safe queue of requests, have the UI thread push requests into one end of the queue, and have another thread pull the requests off, one at a time, as soon as the previous one either completes or times out, and send the results back to the UI thread? Or am I missing something in the API that already does this?
Thanks!
…R
What should work is to use an
NSOperationQueueinstance, and a number ofNSOperationinstances that perform the various URL requests.First, set up a queue in the class that will be enqueueing the requests. Make sure to keep a strong reference to it, i.e.
Somewhere in the implementation, say the
initmethod:You want basically a serial queue, hence the
maxConcurrentOperationCountof 1.After setting this up, you’ll want to write some code like this:
In this way you send synchronous
NSURLRequests and can handle the error conditions, including by bailing out completely and starting all over (the lines with-cancelAllOperationscalled). These requests will be executed one after the other.You can also of course write custom
NSOperationsubclasses and enqueuing instances of those rather than using blocks, if that serves you.Hope this helps, let me know if you have any questions!