Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

iphone - How to detect change in network with Reachability?

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

-(BOOL)reachable {
    ReachabilityDRC *r = [ReachabilityDRC reachabilityWithHostName:@"google.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];
    if(internetStatus == NotReachable) {
        return NO;
    }
    return YES;
}

But I also want to be notified if there is a change of network, such as wifi dropped, or wifi is back, so I can make changes accordingly.

How can I adjust my method to do something like that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...