1.添加framework:
将SystemConfiguration.framework 添加进工程。
2.下载Reachability
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
复制里面的Reachability.h和Reachability.m到项目中。
3.调用代码:
- //判断当前的网络是3g还是wifi
- -(NSString*)GetCurrntNet
- {
- NSString* result;
- Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
- switch ([r currentReachabilityStatus]) {
- case NotReachable:// 没有网络连接
- result=nil;
- break;
- case ReachableViaWWAN:// 使用3G网络
- result=@"3g";
- break;
- case ReachableViaWiFi:// 使用WiFi网络
- result=@"wifi";
- break;
- }
- return result;
- }
例子:
- //
- // ViewController.h
- // NetworkStatusDemo
- //
- // Created by Fox on 12-3-15.
- // Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
- //
- #import
- #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
- // NetworkStatusDemo
- //
- // Created by Fox on 12-3-15.
- // 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