How to detect change in network with Reachability?

爱⌒轻易说出口 提交于 2019-11-29 06:49:58
Reno Jones

Another possible solution is to add a NS Notification in "application didfinishlaunching":

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkForReachability) name:kReachabilityChangedNotification object:nil];

and in checkForReachability method do this:

    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    [reachability startNotifier];

    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

    if(remoteHostStatus == NotReachable) {
        //Do something
    }
     else if (remoteHostStatus == ReachableViaWiFi) {
    // Do something
 }
    else{

// Else do something else
}

1- add SystemConfiguration.framework to your project.

2- Download following files from GitHub

Reachability.h
Reachability.m

3- Add these files in your projects

4- add @class Reachability; in YourViewController.h

#import <UIKit/UIKit.h>

@class Reachability;

5- add variable Reachability* internetReachable; in YourViewController.h

#import <UIKit/UIKit.h>

@class Reachability;

@interface YourViewController : UIViewController {
    Reachability* internetReachable;
}

6- add Reachability.h in YourViewController.m

#import "YourViewController.h"
#import "Reachability.h"

7- add following lines in -(void)ViewDidLoad in YourViewController.m

-(void)ViewDidLoad {
    [[NSNotificationCenter defaultCenter] 
                       addObserver:self 
                       selector:@selector(checkNetworkStatus:) 
                       name:kReachabilityChangedNotification 
                       object:nil];

    internetReachable = [Reachability reachabilityForInternetConnection];
    [internetReachable startNotifier];
}

8- add following function after -(void)viewDidLoad

-(void) checkNetworkStatus:(NSNotification *)notice
{
    // called after network status changes
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus)
    {
        case NotReachable:
        {
            NSLog(@"The internet is down.");
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");
            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");
            break;
        }
    }
}

Now every change of internet connection you will see log in console.

I've used the excellent extension to the Reachability class that the Donoho Design Group has put together. It has notifications that allow you to be alerted when the network status changes.

http://blog.ddg.com/?p=24

Good luck

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!