IOS网络篇:网络状态的监控Reachability

来源:互联网 发布:黑马程序员小马哥 编辑:程序博客网 时间:2024/06/11 19:06

判断设备网络连接情况。相对于苹果官方的Reachability,这是一个更加高级、更加好用的Reachability,支持ARC、支持block、使用GCD方式来通知网络的变化。 [Code4App.com]

Reachability链:https://github.com/tonymillion/Reachability

<span style="font-size:14px;">@interface ViewController ()@property (nonatomic,strong)Reachability* reachability;@end</span>


<span style="font-size:14px;">- (void)viewDidLoad {        [super viewDidLoad];    // 监听网络状态发生改变    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netWorkStateChange) name:kReachabilityChangedNotification object:nil];    // 获得Reachability对象    self.reachability = [Reachability reachabilityForInternetConnection];    // 开始监听网络    [self.reachability startNotifier];    }/** *  状态改变 */- (void)netWorkStateChange{    if ([self isEnableWif])    {        NSLog(@"WIFI");    }else if ([self isEnable3G])    {        NSLog(@"3G");    }else    {        NSLog(@"无网络");    }}- (void)dealloc{    // 停止监听网络    [self.reachability stopNotifier];    // 移除    [[NSNotificationCenter defaultCenter] removeObserver:self];}/** *  是否为Wif环境 */- (BOOL)isEnableWif{    return [[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] !=NotReachable;}/** *  是否为3G环境 */- (BOOL)isEnable3G{    return [[Reachability reachabilityForInternetConnection] currentReachabilityStatus] !=NotReachable;}</span>



1 0
原创粉丝点击