我正在使用最新的AFNetworking V2.0。如果可达性可用,我已经设置了一系列操作在AFHTTPRequestOperationManager的操作队列上运行。我在appDelegate中设置了一个全局AFHTTPRequestOperationManager,并使用它来检查可达性,当可达性不可用时,我暂停AFHTTPRequestOperationManager的操作队列以避免运行操作。当可达性恢复时,我将isSuspended设为false以重新启动操作。
我现在遇到的问题是,当可达性不可用时,我已将isSuspended设置为YES,操作队列仍然会触发并转到操作的故障块。
这是我的设置,
AppDelegate.m
self.reachManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:API_SERVER_URL]];
self.reachManager.responseSerializer = [AFJSONResponseSerializer serializer];
__block NSOperationQueue *operationQueue = self.reachManager.operationQueue;
[operationQueue setMaxConcurrentOperationCount:1];
__block AppDelegate * weakSelf = self;
[self.reachManager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"not reachable");
[operationQueue setSuspended:YES];
[weakSelf showReachabilityAlert:YES];
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
[weakSelf showReachabilityAlert:NO];
[operationQueue setSuspended:NO];
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
[weakSelf showReachabilityAlert:NO];
[operationQueue setSuspended:NO];
break;
default:
[weakSelf showReachabilityAlert:NO];
[operationQueue setSuspended:YES];
break;
}
}];
[self.reachManager.reachabilityManager startMonitoring];
查看控制器
AppDelegate *ad = [[UIApplication sharedApplication] delegate];
NSMutableArray *mutableOperations = [NSMutableArray array];
NSArray * data = [NSArray arrayWithObjects:@"media", @"analysis", nil];
for(NSString * c in data)
{
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:API_SERVER_SECTION_URL, c]];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: received for tag %@", c);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error message : %@", error);
}];
[mutableOperations addObject:op];
}
NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
NSLog(@"%d of %d complete", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
NSLog(@"All operations in batch complete");
}];
//Check the reachability and suspend the opearation queue if there is no reachability
if([ad.reachManager.reachabilityManager isReachable])
[ad.reachManager.operationQueue setSuspended:NO];
else
[ad.reachManager.operationQueue setSuspended:YES];
[ad.reachManager.operationQueue addOperations:operations waitUntilFinished:YES];
当互联网不存在时,如何暂停操作队列?互联网回来后重启队列?
谢谢, 安东尼
答案 0 :(得分:2)
如果有人感兴趣,我已使用最终代码编辑了我之前的代码。