1

I am downloading a file from the web. File size is big some times may reach up to 100MBs some times, I want to continue downloading while to app goes to background or when the device is locked. For this i am using AFNetworking 3.0

[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:myIdentifier];

It works fine as long as i am on WiFi. When i turn off WiFi and turn on my cellular network which is 4G, it stops responding and i get no data as a result of my download request. If i use

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

every thing was fine except my download will not continue when the app goes to background.

I have also checked allowsCellularAccess on NSURLSessionConfiguration and NSURLRequest and object which is YES, but my download does not work when on cellular network.

Here is my full code

 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:myIdentifier];
  configuration.discretionary = YES;
  configuration.sessionSendsLaunchEvents = YES;
  AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
  NSURL *URL = [NSURL URLWithString:downloadUrl];
  NSURLRequest *request = [NSURLRequest requestWithURL:URL];
  NSLog(@"Allow Cellular Network : %d",request.allowsCellularAccess);
  NSLog(@"Allow Cellular Network for session: %d",configuration.allowsCellularAccess);
  NSLog(@"Resource timneout interval: %f",configuration.timeoutIntervalForResource);
  NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
    dispatch_async(dispatch_get_main_queue(), ^{
      [self callProgressBlocksForUrl:lesson.archiveUrl withProgress:downloadProgress.fractionCompleted];
    });

  } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
    NSLog(@"Getting Path for File saving");

return  [NSURL fileURLWithPath:fullPath];
   } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

     NSHTTPURLResponse * myresponse = (NSHTTPURLResponse *)response;
     NSLog(@"Video downloaded, headers: %@", [myresponse.allHeaderFields description]);


  }];
Madu
  • 4,849
  • 9
  • 44
  • 78

2 Answers2

2

You should not be setting the discretionary flag. That tells the OS to wait to download the data until a convenient time (which, IIRC, basically means when the device is A. asleep, B. on power, and C. connected to Wi-Fi).

dgatwood
  • 10,129
  • 1
  • 28
  • 49
0

I guess discretionary flag might create the problem. As said by apple in documentation that discretionary flag allow the download when device have convenient time and convenient resources.

Discretionary

CrazyPro007
  • 1,006
  • 9
  • 15