美文网首页
监听网络状态

监听网络状态

作者: himyfairy | 来源:发表于2016-06-13 09:22 被阅读9次
    • 在项目中导入Reachability.h和Reachability.m文件,地址:Reachability

    • ViewController.h:

    #import "ViewController.h"
    #import "Reachability.h"
    @interface ViewController ()
    @property (nonatomic, strong) Reachability *reach;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netWorkChange) name:kReachabilityChangedNotification object:nil];
        self.reach = [Reachability reachabilityForInternetConnection];
        [self.reach startNotifier];
        
    }
    
    - (void)dealloc
    {
        [self.reach stopNotifier];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    
    - (void)netWorkChange
    {
        /*
         NotReachable = 0,
         ReachableViaWiFi,
         ReachableViaWWAN
         */
        switch ([self.reach currentReachabilityStatus]) {
            case 0:
                NSLog(@"没有网");
                break;
            case 1:
                NSLog(@"WiFi");
                break;
            default:
                NSLog(@"蜂窝数据");
                break;
        }
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:监听网络状态

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