使用Reachability判断网络和应用程序网络的实时监控

iOS网络状态检测
本文介绍了一个iOS应用中实现网络状态检测的方法,通过Reachability类来判断当前设备是处于3G网络还是WiFi网络,并且能够在网络状态发生变化时进行通知。

关于Reachability的类倒入并添加SystemConfiguration.framework

/判断当前的网络是3g还是wifi

-(NSString*)GetCurrntNet
{
    NSString* result;
    Reachability *r = [ReachabilityreachabilityWithHostName:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        caseNotReachable:// 没有网络连接
            result=nil;
            break;
        caseReachableViaWWAN:// 使用3G网络
            result=@"3g";
            break;
        caseReachableViaWiFi:// 使用WiFi网络
            result=@"wifi";
            break;
    }
    return result;
}

// 在应用程序启动的时候加入网络的检测

@classReachability;

@interfaceMyAppDelegate: NSObject<UIApplicationDelegate>

{    Reachability*hostReach;} 

@end


// MyAppDelegate.m 

- (void)reachabilityChanged:(NSNotification*)note{ 

Reachability* curReach= [note object]; 

NSParameterAssert([curReach isKindOfClass: [Reachabilityclass]]); 

NetworkStatusstatus= [curReach currentReachabilityStatus]; 

if(status == NotReachable) {    

UIAlertView*alert= [[UIAlertViewalloc] initWithTitle:@"AppName""                                                     

    message:@"NotReachable"delegate:nil                                              

cancelButtonTitle:@"YES"otherButtonTitles:nil];        

 [alert show];        

 [alert release]; 

}} 

- (void)applicationDidFinishLaunching:(UIApplication *)application { 

// ... 

// 监测网络情况 

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

hostReach = [[Reachability reachabilityWithHostName:@"www.google.com"] retain]; 

[hostReach startNotifer]; 

// ...}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值