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

作者: 天听云道 | 来源:发表于2016-03-04 13:13 被阅读410次

首先导入 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];
        
    }
}

相关文章

网友评论

  • Ths:有个小问题,为什么它会调用两次
    Ths:@天听云道 是的
    天听云道:@Ths 你是不是在电脑上用模拟器测试的?

本文标题:24、[ iOS ] 网络监听 - 通知

本文链接:https://www.haomeiwen.com/subject/gpdokttx.html