在 AFNetworking 重新连接网络时恢复所有上传任务

Posted

技术标签:

【中文标题】在 AFNetworking 重新连接网络时恢复所有上传任务【英文标题】:Resume all upload tasks when network re-connect in AFNetworking 【发布时间】:2016-06-16 10:55:02 【问题描述】:

我正在使用AFNetworking 3.0。我已经使用后台会话成功上传了任务。现在我想根据网络可达性暂停和恢复所有任务。就像没有网络时暂停任务和网络重新连接时恢复任务一样。

代码:

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。 即使应用程序在后台,任何人都可以知道如何调用可达性块吗?

【讨论】:

***.com/questions/22197630/…

以上是关于在 AFNetworking 重新连接网络时恢复所有上传任务的主要内容,如果未能解决你的问题,请参考以下文章