如何通过Reachability检测网络变化?

时间:2011-11-11 19:30:58

标签: iphone objective-c cocoa-touch reachability

我目前正在使用以下方法检查viewDidLoad上的网络连接:

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

但我也希望在网络发生变化时收到通知,例如wifi掉线或wifi恢复,所以我可以相应地进行更改。

如何调整方法以执行类似的操作?

3 个答案:

答案 0 :(得分:9)

1-将SystemConfiguration.framework添加到您的项目中。

2-从GitHub

下载以下文件
Reachability.h
Reachability.m

3-在项目中添加这些文件

4-在@class Reachability;

中添加YourViewController.h
#import <UIKit/UIKit.h>

@class Reachability;

5-在Reachability* internetReachable;

中添加变量YourViewController.h
#import <UIKit/UIKit.h>

@class Reachability;

@interface YourViewController : UIViewController {
    Reachability* internetReachable;
}

6-在Reachability.h

中添加YourViewController.m
#import "YourViewController.h"
#import "Reachability.h"

7-在-(void)ViewDidLoad

YourViewController.m添加以下行
-(void)ViewDidLoad {
    [[NSNotificationCenter defaultCenter] 
                       addObserver:self 
                       selector:@selector(checkNetworkStatus:) 
                       name:kReachabilityChangedNotification 
                       object:nil];

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

8-在-(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;
        }
    }
}

现在,每次更改互联网连接都会看到登录控制台。

答案 1 :(得分:6)

另一种可能的解决方案是在“application didfinishlaunching”中添加NS Notification:

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

并在checkForReachability方法中执行此操作:

    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
}

答案 2 :(得分:0)

我使用了Donoho Design Group所组合的Reachability类的优秀扩展。它具有通知,允许您在网络状态更改时收到警报。

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

祝你好运