These delegate methods will not be called if:
The application already works when tasks are completed;
The application was interrupted by double-clicking on the home button of the device and manually killed it; or
If you did not start the NSURLSession background with the same identifier.
So the obvious questions are:
How did the application stop? If this is not completed or if it did not complete correctly (for example, you manually kill it by double-clicking the home button), this will prevent these delegate methods from getting.
Do you generally see a call to handleEventsForBackgroundURLSession ?
Are you doing this on a physical device? This behaves differently on the simulator.
The bottom line is not enough here to diagnose the exact problem, but these are common reasons why the delegate method cannot be called.
You later said:
This is actually the first time I use the NSURLSession class. My actual requirement is when the download (all images) is completed, then I can get the images from the document directory and I can show in the UICollectionView .
I follow this guide from APPCODA. Here is the link http://appcoda.com/background-transfer-service-ios7
If this is your requirement, then the NSURLSession background may be full. It is slower than the standard NSURLSession , and more complex. Use only background sessions if you really need large downloads to continue in the background after the application is paused / terminated.
This tutorial that you are referencing seems like a bearable introduction to a rather complicated topic (although I disagree with the implementation of URLSessionDidFinish... as described in the comments). I would do something like:
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
The question in my opinion is whether you really need a background session if you just upload images to view the collection. I would only do this if there were so many images (or they were so large) that they could not be loaded enough while the application was still running.
For completeness, I will share a full demo of downloading phonograms below:
// AppDelegate.m #import "AppDelegate.h" #import "SessionManager.h" @interface AppDelegate () @end @implementation AppDelegate // other app delegate methods implemented here // handle background task, starting session and saving // completion handler - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler { [SessionManager sharedSession].savedCompletionHandler = completionHandler; } @end
and
// SessionManager.h @import UIKit; @interface SessionManager : NSObject @property (nonatomic, copy) void (^savedCompletionHandler)(); + (instancetype)sharedSession; - (void)startDownload:(NSURL *)url; @end
and
// SessionManager.m #import "SessionManager.h" @interface SessionManager () <NSURLSessionDownloadDelegate, NSURLSessionDelegate> @property (nonatomic, strong) NSURLSession *session; @end @implementation SessionManager + (instancetype)sharedSession { static id sharedMyManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedMyManager = [[self alloc] init]; }); return sharedMyManager; } - (instancetype)init { self = [super init]; if (self) { NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"foo"]; self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; } return self; } - (void)startDownload:(NSURL *)url { [self.session downloadTaskWithURL:url]; } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { NSLog(@"%s: %@", __FUNCTION__, downloadTask.originalRequest.URL.lastPathComponent); NSError *error; NSURL *documents = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:false error:&error]; NSAssert(!error, @"Docs failed %@", error); NSURL *localPath = [documents URLByAppendingPathComponent:downloadTask.originalRequest.URL.lastPathComponent]; if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:localPath error:&error]) { NSLog(@"move failed: %@", error); } } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"%s: %@ %@", __FUNCTION__, error, task.originalRequest.URL.lastPathComponent); } - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { NSLog(@"%s", __FUNCTION__); // UILocalNotification *notification = [[UILocalNotification alloc] init]; // notification.fireDate = [NSDate date]; // notification.alertBody = [NSString stringWithFormat:NSLocalizedString(@"Downloads done", nil. nil)]; // // [[UIApplication sharedApplication] scheduleLocalNotification:notification]; if (self.savedCompletionHandler) { self.savedCompletionHandler(); self.savedCompletionHandler = nil; } } @end
And finally, the code for the view controller that initiates the request:
// ViewController.m #import "ViewController.h" #import "SessionManager.h" @implementation ViewController - (IBAction)didTapButton:(id)sender { NSArray *urlStrings = @[@"http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/s72-55482.jpg", @"http://spaceflight.nasa.gov/gallery/images/apollo/apollo10/hires/as10-34-5162.jpg", @"http://spaceflight.nasa.gov/gallery/images/apollo-soyuz/apollo-soyuz/hires/s75-33375.jpg", @"http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-134-20380.jpg", @"http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-140-21497.jpg", @"http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-148-22727.jpg"]; for (NSString *urlString in urlStrings) { NSURL *url = [NSURL URLWithString:urlString]; [[SessionManager sharedSession] startDownload:url]; } // explicitly kill app if you want to test background operation // // exit(0); } - (void)viewDidLoad { [super viewDidLoad]; // if you're going to use local notifications, you must request permission UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; } @end