IOS: complete download task when application is in background

Is there no way to start the UPLOAD task when the iOS application is in the background? This is ridiculous. Looking at various things like NSURLSessionUploadTask , dispatch_after and even NSTimer , but nothing works after more than 10 seconds when the application lives after it is placed in the background.

How do other download apps work? Say uploading an image to Facebook and installing the application in the background will result in cancellation of the upload?

Why doesn't iOS have background services or agents like Android and Windows Phone?

This is a critical feature of my application, and works great on other platforms.

Any help is appreciated :(

+6
source share
1 answer

You can continue downloading in the background using iOS 7+ if you use [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:] for configuration when creating an instance of NSURLSession .

Note:

  • you need to use delegate NSURLSession ;

  • You cannot use the completionHandler using factory method methods with background sessions; and

  • you also need to use the uploadTaskWithRequest:fromFile: method, not NSData .

  • your application delegate should implement application:handleEventsForBackgroundURLSession:completionHandler: and grab this completion handler, which you can then call in your NSURLSessionDelegate method NSURLSessionDelegate URLSessionDidFinishEventsForBackgroundURLSession:


By the way, if you do not want to use background NSURLSession , but want to continue the task with a finite length of more than a few seconds after the application leaves the background, you can request more time using the UIApplication method beginBackgroundTaskWithExpirationHandler . This will give you a few minutes to complete any tasks you are working on. See Listing 3-3 in the “Finishing a finite length task” section in the “Background” section of the “Application Status and Multitasking” section in the iOS Application Programming Guide.

 UIApplication *application = [UIApplication defaultApplication]; bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ // Clean up any unfinished task business by marking where you // stopped or ending the task outright. [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; // Start the long-running task and return immediately. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Do the work associated with the task, preferably in chunks. [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }); 
+6
source

Source: https://habr.com/ru/post/969755/


All Articles