2016-06-16 1 views
0

私はAFNetworking 3.0を使用しています。バックグラウンドセッションを使用してタスクを正常にアップロードしました。今、ネットワークの到達可能性に基づいてすべてのタスクを中断し、再開したいと思います。ネットワークが再接続したときにタスクを中断し、タスクを再開します。AFNetworkingでネットワークを再接続すると、すべてのアップロードタスクを再開

コード:

static AFURLSessionManager *manager; 

static dispatch_once_t onceToken; 
dispatch_once(&onceToken, ^{ 

    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"wts.Demo-Upload"]; 
    sessionConfiguration.HTTPMaximumConnectionsPerHost = 20; 
    manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:sessionConfiguration]; 
}); 

[manager setDidFinishEventsForBackgroundURLSessionBlock:^(NSURLSession * _Nonnull session) { 
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
    if (appDelegate.backgroundSessionCompletionHandler) { 
     void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandler; 
     appDelegate.backgroundSessionCompletionHandler = nil; 
     completionHandler(); 
    } 

    NSLog(@"All tasks are finished"); 
}]; 



NSOperationQueue *operationQueue = manager.operationQueue; 

[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { 

    switch (status) { 
     case AFNetworkReachabilityStatusNotReachable: 
      // we need to notify a delegete when internet conexion is lost. 
      // [delegate internetConexionLost]; 
      NSLog(@"No Internet Conexion"); 
      break; 
     case AFNetworkReachabilityStatusReachableViaWiFi: 
      NSLog(@"WIFI"); 
      break; 
     case AFNetworkReachabilityStatusReachableViaWWAN: 
      NSLog(@"3G"); 
      break; 
     default: 
      NSLog(@"Unkown network status"); 
      [operationQueue setSuspended:YES]; 
      break; 
    } 
}]; 
    [manager.reachabilityManager startMonitoring]; 

答えて

1

最後に見つかったソリューション。 まずすべてのアップロードタスクを取得して、再開します。

[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { 

    switch (status) { 
     case AFNetworkReachabilityStatusNotReachable: 
      NSLog(@"No Internet Connection"); 
      break; 
     case AFNetworkReachabilityStatusReachableViaWiFi: 
      NSLog(@"WiFi"); 
     case AFNetworkReachabilityStatusReachableViaWWAN: 
      NSLog(@"3G"); 
      for (NSURLSessionUploadTask *uploadTask in [manager uploadTasks]) { 
       [uploadTask resume]; 
      } 
      break; 
     default: 
      NSLog(@"Unknown network status"); 
      [operationQueue setSuspended:YES]; 
      break; 
    } 
}]; 

上記のコードは、アプリがフォアグラウンドにあるときに問題なく動作します。しかし、setReachabilityStatusChangeBlockは、アプリがバックグラウンドにあるときは決して呼び出されません。 誰でも、到達可能性のブロックを呼び出す方法を知っていても、アプリはバックグラウンドにありますか?

+0

https://stackoverflow.com/questions/22197630/ios-reachability-notification-in-background/44236311#44236311 –

関連する問題