AFNetWorking 监听网络连接的状态

时间:2021-05-31 15:19:51

</pre>在AFNetWorking中有找到AFNetworkReachabilityManager文件,这个文件中处理的都是很网络状态有关的。<p></p><p>其中有一个AFPostReachabilityStatusChange方法,这个方法每次网络状态发生改变时都会调用,所以我在这个方法中发送一个通知,接收到通知后可以根据网络状态判断。</p><p>下面是部分代码</p><p>首先是AFNetworkReachabilityManager文件中:</p><p></p><pre name="code" class="objc">static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusBlock block) {
    AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
    dispatch_async(dispatch_get_main_queue(), ^{
        if (block) {
            block(status);
        }
        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
        NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) };
        [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo];
#warning 网络状态发生改变通知,全局监控网络
        [notificationCenter postNotificationName:@"networking_monitoring_notification" object:nil userInfo:nil];
    });
}

通知的接收者写在了AppDelegate的didFinishLaunchingWithOptions中

- (void)netWorkMonitoring
{
    NSURL *baseURL = [NSURL URLWithString:@"http://baidu.com/"];
    manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
    //开始监控
    [manager.reachabilityManager startMonitoring];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged) name:NETWORKING_MONITORING_NOTIFICATION object:nil];
}
- (void)reachabilityChanged
{
     NSOperationQueue *operationQueue = manager.operationQueue;
     [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
         switch (status) {
             case AFNetworkReachabilityStatusReachableViaWWAN:
             case AFNetworkReachabilityStatusReachableViaWiFi:
                 [operationQueue setSuspended:NO];
                 NSLog(@"----------网络已连接--------");
 
                 break;
             case AFNetworkReachabilityStatusNotReachable:
                 NSLog(@"------------网络未连接--------");
 
             default:
                 [operationQueue setSuspended:YES];
                 break;
         }
     }];

}