Best practice to send a lot of data in background on iOS4 device? Best practice to send a lot of data in background on iOS4 device? multithreading multithreading

Best practice to send a lot of data in background on iOS4 device?


OK, I'll answer my own question.First, like tc said, it's better to have this call on the application delegate, so that the View in the NavigationController can be closed.Second, mark beginning of the background processing with beginBackgroundTaskWithExpirationHandler: and end it with endBackgroundTask: like this:

.h:

UIBackgroundTaskIdentifier bgTask;

.m:

- (void)sendPhoto:(UIImage *)image{  UIApplication *app = [UIApplication sharedApplication];  bgTask = [app beginBackgroundTaskWithExpirationHandler:^{     [app endBackgroundTask:bgTask];     bgTask = UIBackgroundTaskInvalid;  }];  NSLog(@"Sending picture...");  // Init async NSURLConnection  // ....}- (void)connectionDidFinishLoading:(NSURLConnection *)connection {  NSLog(@"Picture sent.");    UIApplication *app = [UIApplication sharedApplication];  if (bgTask != UIBackgroundTaskInvalid) {    [app endBackgroundTask:bgTask];     bgTask = UIBackgroundTaskInvalid;  }}

You have 10 minutes before iOS terminates your app. You can check this time with [app backgroundTimeRemaining]


I'd just use NSURLConnection. It's a bit tricky if you want to send multipart/form-data (see the SimpleURLConnections/PostController.m example). I'd stick it in the app delegate, but I'm lazy like that.

You shouldn't worry about threads at all unless non-blocking I/O (i.e. NSURLConnection) is too slow. Threading has its own overheads, and inter-thread communication is a pain, and deadlocks are terrible.

What you do need to do is start a background task to allow your app to continue executing while backgrounded (end the background task in connectionDidFinishLoading: and connection:didFailWithError). Backgrounded apps are given about 10 minutes to finish executing background tasks.


Use ASIHTTP and setup a Queue. All the information you need can be found here:

http://allseeing-i.com/ASIHTTPRequest/

This is the easiest way to accomplish what you want to accomplish. For sending lots of data, it is better to send in the background to keep the UI responsive. ASIHTTPRequest provides all the methods you need to kick of multiple queries (i.e. progress checks, callbacks, etc).

It's used by tons of great iPhone apps.