iOS网络检测

使用之前请从Apple网站下载示例:点此下载

Reachability 中定义了3种网络状态:

typedef enum : NSInteger {
NotReachable = ,//无网络
ReachableViaWiFi,//wifi
ReachableViaWWAN//3g
} NetworkStatus;

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

    Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
switch ([r currentReachabilityStatus]) {
case NotReachable:
// 没有网络连接
NSLog(@"没有网络连接");
break;
case ReachableViaWWAN:
NSLog(@"使用3g网络");
// 使用3G网络
break;
case ReachableViaWiFi:
NSLog(@"使用wifi网络");
// 使用WiFi网络
break;
}

检测当前网络环境:

// 是否wifi
+ (BOOL) IsEnableWIFI {
return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
} // 是否3G
+ (BOOL) IsEnable3G {
return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}

连接状态实时通知:

#import <UIKit/UIKit.h>
#import "Reachability.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate> {
Reachability *hostReach;
}
@property (strong, nonatomic) UIWindow *window; @end
- (void)reachabilityChanged:(NSNotification *)note {
// 连接改变
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
//处理连接改变后的情况
NetworkStatus status = [curReach currentReachabilityStatus]; if (status == NotReachable) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"你的网络已断开连接"
delegate:nil
cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 监测网络情况
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name: kReachabilityChangedNotification
object: nil];
hostReach = [Reachability reachabilityWithHostName:@"www.google.com"];//可以以多种形式初始化
[hostReach startNotifier];//开始监听,会启动一个run loop
return YES;
}
 
上一篇:Apache -- 压力测试工具ab.exe


下一篇:【下载】支持中文的 jspSmartUpload jar 包