I’ve searched a lot within SO but I can’t find the right answer for my question.
Here the problem:
I’m figuring out the right mechanism to send multiple upload requests within an NSOperation subclass. In particular, this class performs two different operation within its main method:
- First it retrieves data from a local db
- Then it sends the composed data to a web server
Since, these two operations can take time to executed I wrapped them, as already said, within an NSOperation.
To upload data I decided to adopt a sync pattern (I need to sync my application with the number of upload requests that has been successfully submitted to the web server).
To perform a similar upload I’m using ASIHttpRequest in a synch fashion like the following.
for (int i = 0; i < numberOfUploads; i++) {
// 1-grab data here...
// 2-send data here
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
int response = [request responseStatusCode];
if(response == 200)
uploads++;
}
}
So, my questions are:
- is this a valid solution to upload data to a web server?
- is it valid to create
ASIHTTPRequest *requestwithin a background thread? - do I have to use an async pattern? If yes, how to?
Note I’m using ASIHttpRequest for sync requests but I think the same pattern could be applied with NSUrlConnection class through
sendSynchronousRequest:returningResponse:error:
Thank you in advance.
To answer your questions directly:
Yes, calling an
NSUrlConnection(in your case, ASI wrapper) with a sync call is valid in anNSOperation.You can create
NSUrlConnectionsin background threads, but there are a couple of things to remember here:If you use it on a background thread, you have to either call the synchronous methods, or you have to keep the thread alive yourself. Using the
asyncin anNSOperationis explained pretty well here: How do I do an Asychronous NSURLConnection inside an NSOperation? I have used this pattern and it works well.NSUrlConnnectionDelegate callbacks call back to the thread that theNSUrlConnectionwas created on. Just something to remember.You do not have to use the
asyncpattern, but you can. The async pattern provides more flexibility. For example, if you need to cancel the operation, you have the ability to cancel theNSUrlConnectionrequest with theasyncpattern. With the sync pattern, you are forced to let it run (unless you kill the thread explicitly).One note: I would reconsider using ASI as it is no longer supported.
AFNetworkingseems to be the most popular replacement, though I chose to start usingNSUrlConnectiondirectly.