How to detect change in network with Reachability?

后端 未结 3 454
刺人心
刺人心 2020-12-18 00:57

I\'m currently checking network connection on viewDidLoad using this:

-(BOOL)reachable {
    ReachabilityDRC *r = [ReachabilityDRC reachabilityW         


        
3条回答
  •  無奈伤痛
    2020-12-18 01:24

    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 
    
    @class Reachability;
    

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

    #import 
    
    @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.

提交回复
热议问题