使用Reachability实时监测网络

1.从官网出下载Reachability.h/m文件,拖入工程
https://developer.apple.com/library/ios/samplecode/Reachability/Listings/Reachability_Reachability_m.html

2.调用Reachability.h头文件,并创建全局变量Reachability *internetReachability;

3.在AppDelegate的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中创建通知

 //添加一个系统通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    //初始化
    internetReachability=[Reachability reachabilityForInternetConnection];
    //通知添加到Run Loop
    [internetReachability startNotifier];
    [self updateInterfaceWithReachability:internetReachability];

4.实现通知方法

- (void) reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    [self updateInterfaceWithReachability:curReach];
}

5.监测网络状态方法

- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
    NetworkStatus netStatus = [reachability currentReachabilityStatus];
    switch (netStatus) {
        case NotReachable:
            NSLog(@"====当前网络状态不可用=======");
            break;
        case ReachableViaWiFi:
            NSLog(@"====当前网络状态为Wifi=======");
            break;
        case ReachableViaWWAN:
            NSLog(@"====当前网络状态为流量=======keso");
            break;
    }
}

注:
1.此方法能监测所有页面的网络状态,可是要在当前页面获取当前网络状态则需要使用AFNetWorking,如果不嫌麻烦那就一个一个写.
2.如果有更好的方法请留言,谢谢.

你可能感兴趣的:(使用Reachability实时监测网络)