21

I have an app that needs to send data (using POST) to a server. This function has to be on one of the NavigationController sub-controllers and user should be able to navigate away from this controller and/or close the app (only iPhone4/iOS4 will be supported). Should I use threads/NSOperations or/and send data using existing asynchronous methods? Any ideas/best practices how to implement this?

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
cocoapriest
  • 1,869
  • 3
  • 22
  • 36

5 Answers5

31

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]

Community
  • 1
  • 1
cocoapriest
  • 1,869
  • 3
  • 22
  • 36
  • well, I do see the 10 min time limit in lots of posts, but there are mentions that you can further extend the time limit by calling beginBackgroundTaskWithExpirationHandler: again Refer: http://stackoverflow.com/questions/3291840/iphone-app-running-http-requests-while-application-in-background/3587547#3587547 – palaniraja May 30 '11 at 14:28
  • @CocoaPriest did u get past the 10min time limit? – owen gerig Jan 04 '12 at 15:48
  • do you need to do anything in applicationDidEnterBackground? – dips Aug 03 '12 at 17:55
  • I get errors when I declare the UIBackgroundTaskIdentifier bgTask; in my header, should it be outside of the "@interface" call? XCode doesnt complain when I post it below "@end" but it still doesnt work – Kyle C Sep 18 '12 at 01:07
  • What will happen if I don't call endBackgroundTask method. – quang thang Jun 01 '16 at 04:00
4

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.

tc.
  • 33,468
  • 5
  • 78
  • 96
  • ok, and that's the question: how do I allow the already started thread (here: NSURLConnection) to continue executing in the background after app closing? – cocoapriest Oct 14 '10 at 13:35
1

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.

Jordan
  • 21,746
  • 10
  • 51
  • 63
  • 1
    Because good networking code doesn't require a separate thread. What do you mean "setup an async queue"? A NSOperationQueue? That's completely unnecessary. – tc. Oct 14 '10 at 12:09
  • I meant having the post run in the background to not tie up the UI. – Jordan Oct 14 '10 at 12:14
  • And how could I keep this Queue for executing in background (after closing the app)? – cocoapriest Oct 14 '10 at 15:16
  • Background processing such as what you want to do is not allowed by Apple, for Apps that are not in the foreground. Please take a look at the ASIHTTPRequest answer I provided above. It's all you need. – Jordan Oct 14 '10 at 15:45
  • It's allowed on iOS4 for about 10 minutes, like tc said already – cocoapriest Oct 14 '10 at 15:59
  • You don't need to set up an NSOperationQueue/dispatch queue/whatever to run stuff in the background. When in doubt, I'd just use NSURLConnection; I haven't found a compelling reason to use ASIHTTPConnection yet. – tc. Nov 21 '10 at 06:05
  • Jordan, you're talking about running connection in a 'background thread' while the app it is still running in the foreground. Konstantin is talking about running connection the the app exit to the background, which IS allowed after iOS 4. – Joseph Lin Jun 29 '11 at 19:46
  • 1
    ASIHttpRequest has a flag called shouldContinueWhenAppEntersBackground. Set it to yes and you get backgrounding for free. – Mugunth Aug 08 '11 at 15:11
0

I'd definitely suggest a second thread for any long running process which need to run whilst the user is doing something else.

Another thing you will need to think about is what is going to happen if the user starts the process and then hits the home button. How will the server interaction be effected by being interrupted? Can it continue when the user next enters the app? etc.

drekka
  • 20,957
  • 14
  • 79
  • 135
  • these are exactly issues I need to investigate. If sending data in the new thread, do I need to use async oder sync methods to post data?.. – cocoapriest Oct 13 '10 at 23:35
0

I'd like to support the post that mentions:

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
      [app endBackgroundTask:bgTask]; 

      bgTask = UIBackgroundTaskInvalid;
}];

But also point out that you may want to encapsulate your unit of work in an NSOperation subclass as well. This will make it extremely re-useable and, when combined with NSOperationQueue, automatically handle threading and what not. Then later, when you want to change your code, or have it appear in a different location in your app, it will be trivial to move or edit.

One note about using the operation queue, is that in this case you will actually want to send a synchronous url request from within the queue. This will let you not have to worry about concurrent operations. Here is the link that you may find helpful:

http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/

Dave Chen
  • 10,887
  • 8
  • 39
  • 67
Jackie Treehorn
  • 826
  • 1
  • 7
  • 5
  • Synchronous connections aren't advisable. Yes, you're trying to overcome the problem of the queue's runloop quitting before your connection has time to complete (and send the relevant delegate callback messages), but synchronous connections are not the best way to do it. – MattyG Aug 30 '11 at 07:18