美文网首页自鉴
监控iOS网络状态改变

监控iOS网络状态改变

作者: wangwei_1916 | 来源:发表于2016-09-29 12:53 被阅读51次

    1.在github下载Reachability框架
    https://github.com/tonymillion/Reachability
    2.导入系统框架 SystemConfiguration.framework

    Snip20160929_8.png
    3.导入Reachability框架里面 Reachability.h,Reachability.m的两个文件

    4.在appDelegate.m 实现

    #import "AppDelegate.h"

    #import "Reachability.h"

    @interface AppDelegate ()

    @property(nonatomic,strong)Reachability*hostReah;

    /// 记录网络改变之前的网络状态@property(nonatomic,assign)NetworkStatus status;```

    @end

    @implementation AppDelegate

    -(BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //开启网络状况的监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:)name:kReachabilityChangedNotification object:nil];
    
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    [reach startNotifier];
    
    
    //开始监听,会启动一个runloop
    
    [self.hostReach startNotifier];
    
    
    return YES;
    

    }
    /// 通知 调用的方法
    -(void)reachabilityChanged:(NSNotification *)notification

       Reachability *reach = [notification object];
        if([reach isKindOfClass:[Reachability class]]){
            NetworkStatus status = [reach currentReachabilityStatus];
            //如果网络状态发生改变
            if (status != self.status) {
                //记录当前网络状态
                self.status = status;
                UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil message:[self isInternetWith:status] delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
                [alert show];
            }
            }
    }
    ///返回根据status返回当前网络状态
    
    -(NSString*)isInternetWith:(NetworkStatus)status
    ```{
        switch (status) {
            case NotReachable:
                return @"没网";
                break;
            case ReachableViaWiFi:
                return @"WIFI上网";
                break;
            case ReachableViaWWAN:
                return @"移动上网";
                break;
                
            default:
                break;
        }
    }```

    相关文章

      网友评论

      • 小冰山口:楼主屌爆了,大家让开。不要被炸伤了

      本文标题:监控iOS网络状态改变

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