我正在使用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];
答案 0 :(得分: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;
}
}];
当app在前台时,上面的代码工作正常。但是当app在后台时,setReachabilityStatusChangeBlock
永远不会被调用。
任何人都可以知道如何调用可达性块甚至应用程序在后台吗?