handleEventsForBackgroundURLSession never called when a downloadTask finished

Viewed 5694

I am using AFURLSessionManager, and set the manager as a singleton instance.

- (AFURLSessionManager *)backgroundSession
{
    static AFURLSessionManager *backgroundSession = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.testBackground.BackgroundDownload.BackgroundSession1234"];
    backgroundSession = [[AFURLSessionManager alloc]initWithSessionConfiguration:config];
    [backgroundSession setDownloadTaskDidWriteDataBlock:^(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite){
        NSLog(@"i am downloading my id = %d progress= %f",downloadTask.taskIdentifier, totalBytesWritten*1.0/totalBytesExpectedToWrite);
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    }];
    [backgroundSession setDownloadTaskDidFinishDownloadingBlock:^NSURL *(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location){
        NSLog(@"download finished");
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        return location;

    }];
    });
    return backgroundSession;
}
//assign a download task
NSURLSessionDownloadTask *task = [manager1 downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        return targetPath;
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog("%download success");
}];
[task resume];

I found that when I switch the app to the background the download task is running but when it was finished, the system call handleEventsForBackgroundURLSession will never be called.I am feeling that I have missed some setting or options. Any idea will be useful for me, thanks a lot.

- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler;
2 Answers
Related