iOS---检测网络状态

 
// the network state of the device for Reachability 1.5.
typedef enum {
    NotReachable = 0,  //无连接
    ReachableViaCarrierDataNetwork, //使用3G/GPRS网络
    ReachableViaWiFiNetwork  //使用WiFi网络
} NetworkStatus;

// the network state of the device for Reachability 2.0.
typedef enum {
    NotReachable = 0,  //无连接
    ReachableViaWiFi,  //使用3G/GPRS网络
    ReachableViaWWAN  //使用WiFi网络
} NetworkStatus;

比如检测某一特定站点的接续状况,可以使用下面的代码:

Reachability *r =[Reachability  reachabilityForLocalWiFi];
switch ([r currentReachabilityStatus]) {
    case NotReachable:
        // 没有网络连接
        break;
    case ReachableViaWWAN:
        // 使用3G网络
        break;
    case ReachableViaWiFi:
        // 使用WiFi网络
        break;
}
 
 

将Reachability.h 和 Reachability.m 加到自己的项目中,并用 SystemConfiguration.framework,就可以使用了。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{  

       if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus==NotReachable)||([Reachability reachabilityForLocalWiFi].currentReachabilityStatus==NotReachable))   {  

        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"警告" message:@"您的设备暂时没有可用的网络!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];  

        [alert show];   

    }  

 } 

 

 

添加实时监测网络的变化

在appDeletegate.m中引用

#import "Reachability.h"
@interface AppDelegate ()
@property (nonatomic,strong)Reachability *conn;
@end

@implementation AppDelegate

- (void)reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [curReach currentReachabilityStatus];
    switch (status)
    {
        case NotReachable:
            // 没有网络连接
            NSLog(@"网络没有连接");
            break;
        case ReachableViaWWAN:
            // 使用2G/3G网络
            NSLog(@"连接的蜂窝数据");
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络
            NSLog(@"连接的wifi");
            break;  
    }
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //添加监测
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    self.conn = [Reachability reachabilityForInternetConnection];
    [self.conn startNotifier];
    return YES;
}

posted @ 2015-03-30 17:09  蓝色的风1203  阅读(178)  评论(0编辑  收藏  举报