Reputation: 1477
I am using asynchronous NSURLConnection
to upload my images. I have a minor requirement and I want to know what is the efficient way to achieve it. When I press upload button then I pop my current view controller, so what I need is my upload operation keeps going on background even if I am at any part of my navigation controller stack. I can navigate and be anywhere but still want that upload to happen in background.
I just need tips on what is the efficient and elegant way to achieve that.
Upvotes: 2
Views: 1152
Reputation: 53551
You need to separate your uploading logic from the view controller that triggers it.
Perhaps you could create an "upload manager" class that handles all the uploads from different view controllers in a queue and just notifies the interested view controllers about things like progress, errors, etc. (e.g. via notifications).
It could then also manage background task identifiers for continuing uploads when your app is sent to the background by pressing the home button.
Upvotes: 1
Reputation: 23359
In this instance what you mean by "on background" is - on another thread. Thus you are talking about multithreading. Not to be confused with background processing which is in the case of iOS - tasks that execute while the application is in the background.
In order to do what you wish to do, I recommend using GCD
(Grand Central Dispatch), you can dispatch
a block
of code to another thread (other then the main thread) in order to achieve a smooth "background like" processing - please remember that the main thread deals with everything UI related so, in order to not block it (literally) it is necessary to perform any long lasting processes such as downloading/uploading to and from remote sources on another thread.
This is an example of what you could so:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Prepare your upload request
NSError * _urlError = nil;
NSHTTPURLResponse * _responseHeaders = nil;
NSData * responseData = [NSURLConnection sendSynchronousRequest:uploadHTTPRequest
returningResponse:&_responseHeaders
error:&_urlError];
// by this line, we have a response
dispatch_async( dispatch_get_main_queue(), ^{
// Update UI or whatever, this is where you "rejoin" the main thread if needed.
// Maybe for development, show a UIAlertView...
});
});
Upvotes: 3