Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLSession background download not working

I am trying to download a number of files using NSURL background session with nsurlsessiontask. Everything works like charm when the app is running in debugging mode (when the device is connected to Xcode), doesn't work when unplugging device (iPad) from Xcode.

I am using Xcode 7.3.1 with iOS 9.3.5.I have already spent weeks tracing this strange behavior but haven't got any breakthroughs. May be I missing something to implement background download. Recently upgraded Xcode to 8.1.2 and iOS to 10.2.1 assuming upgradation might solve the issue but it is not.

like image 679
gagan sharma Avatar asked Feb 13 '17 10:02

gagan sharma


1 Answers

refer below link and follow steps

https://www.appcoda.com/background-transfer-service-ios7/

  -(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session{
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;

// Check if all download tasks have been finished.
[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
    if ([downloadTasks count] == 0) {
        if (appDelegate.backgroundTransferCompletionHandler != nil) {
            // Copy locally the completion handler.
            void(^completionHandler)() = appDelegate.backgroundTransferCompletionHandler;

            // Make nil the backgroundTransferCompletionHandler.
            appDelegate.backgroundTransferCompletionHandler = nil;

            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                // Call the completion handler to tell the system that there are no other background transfers.
                completionHandler();

                // Show a local notification when all downloads are over.
                UILocalNotification *localNotification = [[UILocalNotification alloc] init];
                localNotification.alertBody = @"All files have been downloaded!";
                [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
            }];
        }
    }
}];

}

like image 192
Sagar Rathode Avatar answered Sep 29 '22 12:09

Sagar Rathode