美文网首页
Reachability判断网络是否可用

Reachability判断网络是否可用

作者: 求长生 | 来源:发表于2020-05-27 16:50 被阅读0次

///开启网络状况的监听
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];

self.reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
[self.reach startNotifier]; //开始监听,会启动一个run loop

//通知
-(void)reachabilityChanged:(NSNotification*)note
{
Reachability * reach = [note object];
NSParameterAssert([reach isKindOfClass: [Reachability class]]);
NetworkStatus status = [reach currentReachabilityStatus];

// //用于检测是否是WIFI
// NSLog(@"%d",([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable));
// //用于检查是否是3G
// NSLog(@"%d",([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable));

if (status == NotReachable) {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"网络已断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alertView show];
    NSLog(@"Notification Says Unreachable");
}else if(status == ReachableViaWWAN){
    
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"移动网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alertView show];
    NSLog(@"Notification Says mobilenet");
}else if(status == ReachableViaWiFi){
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"WIfi网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alertView show];
    NSLog(@"Notification Says wifinet");
}

}

  • (void)dealloc {
    // 删除通知对象
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

https://www.jianshu.com/p/7854c36f0e90
https://www.cnblogs.com/LiLihongqiang/p/5669687.html

相关文章

网友评论

      本文标题:Reachability判断网络是否可用

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