通过Reachability来判断设备的网络环境,方法比较简单。直接将Reachability.h和Reachability.m加入到工程中,然后添加SystemConfiguration.framework框架,就可以使用了。工程截图:
ViewController.h
// // ViewController.h // NetworkStatusDemo // // Copyright (c) 2012年 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> #import "Reachability.h" @interface ViewController : UIViewController{ IBOutlet UILabel *netstatus; Reachability* status; //网络状态 } @property (retain, nonatomic) IBOutlet UILabel *netstatus; @property (retain, nonatomic) Reachability* status; + (BOOL) IsEnableWIFI; + (BOOL) IsEnable3G; @end
ViewController.m
// // ViewController.m // NetworkStatusDemo // // Copyright (c) 2012年 __MyCompanyName__. All rights reserved. // #import "ViewController.h" #import "Reachability.h" @implementation ViewController @synthesize netstatus; @synthesize status; - (void)viewDidLoad { [super viewDidLoad]; self.status = [[Reachability alloc] init]; status = [Reachability reachabilityWithHostName:@"www.cnblogs.com/foxmin"]; switch ([status currentReachabilityStatus]) { case NotReachable: // 没有网络连接 self.netstatus.text = @"没有网络连接"; break; case ReachableViaWWAN: // 使用3G网络 self.netstatus.text = @"使用3G网络"; break; case ReachableViaWiFi: // 使用WiFi网络 self.netstatus.text = @"使用WiFi网络"; break; } //程序启动时,检查程序的网络环境 if ([ViewController IsEnableWIFI] && ![ViewController IsEnable3G]) { self.netstatus.text = @"使用WiFi网络"; }else if(![ViewController IsEnableWIFI] && [ViewController IsEnable3G]){ self.netstatus.text = @"使用3G网络"; }else self.netstatus.text = @"没有网络连接"; } - (void)viewDidUnload { [self setNetstatus:nil]; [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [netstatus release]; [super dealloc]; } /* *判断是否通过wifi */ + (BOOL) IsEnableWIFI { return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable); } /* *判断是否通过3G */ + (BOOL) IsEnable3G { return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable); } @end