iOS 网络状态实时监测。Reachability 使用
1. 使用之前请从Apple网站下载示例: 官方示例下载地址 Download Sample Code或者:打开xcode ->window->Documentation and API Reference 搜索 Reachability ,即可找到示例下载
然后将Reachability.h 和 Reachability.m 加到自己的项目中,并引用 SystemConfiguration.framework,就可以使用了。
2.实时监测使用
在AppDelegate.h
#import <UIKit/UIKit.h>
#import "Reachability.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong,nonatomic)Reachability *hostReachability;//主机连接模式
@end
在 AppDelegate.m
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
//自定义一个方法,用于在接收通知时进行调用
-(void)reachabilityChanged:(NSNotification *)note
{
Reachability *cuRechMode = [note object];
if (cuRechMode == self.hostReachability)
{
NetworkStatus status = [cuRechMode currentReachabilityStatus];
switch (status) {
case NotReachable:
NSLog(@"无网络状态!");
break;
case ReachableViaWiFi:
NSLog(@"通过wifi 进行网络连接!");
break;
case ReachableViaWWAN:
NSLog(@"可以通过2G/3G 网络进行连接!");
break;
default:
break;
}
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//在通知中心注册通知,当连接状态发生变化时发布通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
//通过主机连接模式获取一个连接状态
self.hostReachability = [Reachability reachabilityWithHostName:@"www.apple.com"];
//开始监测网络状态
[self.hostReachability startNotifier];
return YES;
}
//检测当前网络环境:
// 是否wifi
+ (BOOL) IsEnableWIFI {
return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}
// 是否3G
+ (BOOL) IsEnable3G {
return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}