24、[ iOS ] 网络监听 - 通知

首先导入 Reachability 这个第三方库,在 AppDelegate 中

@property (nonatomic, strong) Reachability *net;
  // ------开启网络状况监听
  [self startNetMonitor];

然后实现其方法

/**
 * 网络检测
 */
// -----------------------------------------------------------------
- (void)startNetMonitor {
    
    // ------开启网络状况监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange:) name:kReachabilityChangedNotification object:nil];
    self.conn = [Reachability reachabilityWithHostName:@"www.apple.com"];
    [self.conn startNotifier];
    
}

- (void)networkStateChange:(NSNotification *)note
{
    Reachability *currReach = [note object];
    NSParameterAssert([currReach isKindOfClass:[Reachability class]]);
    
    [self updateInterfaceWithReachability:currReach];
    
}
- (void) updateInterfaceWithReachability: (Reachability*) curReach
{
    NetworkStatus status = [curReach currentReachabilityStatus];
    
    if (status == NotReachable) {
        
        // ------没有网络弹出提示框
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"
                                                                                 message:@"当前网络不可用,请检查网络设置"
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];

        [alertController addAction:cancelAction];
        
        [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
        
    }
}

你可能感兴趣的:(24、[ iOS ] 网络监听 - 通知)