目前IOS的网络应用程序,都是需要进行网络连接的判断的,如果没有这个连接的判断,在APP的审核是无法通过的。那么今天将讲解一个比较常用的基础类库,用于判断网络的连接状况,这个类,就是 Reachability类库。
具体使用步骤:
1.首先是将Reachability类库的头文件和M文件同时导入到工程当中。
2.添加SystemConfiguration.framework。
具体使用,分如下几个情况:
1.直接检查网络的连接状况。
Reachability *r = [Reachability reachabilityWithHostName:@“www.apple.com”];
switch ([r currentReachabilityStatus]) {
case NotReachable:
// 没有网络连接
break;
case ReachableViaWWAN:
// 使用3G网络
break;
case ReachableViaWiFi:
// 使用WiFi网络
break;
}
注意:这种方法,是在需要获取数据的时候,只能够判断一次。
2.判断是3G网络还是无线局域网。
// 是否WIFI
+ (BOOL) IsEnableWIFI {
return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}
// 是否3G
+ (BOOL) IsEnable3G {
return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}
3. 实时的去判断网络的连接情况。
通知是最好的实现方法。另外,需要注意的一点就是Reachability类,其实还有一个1.5版本,2.0版本的问题。现在基本上都是使用2.0版本。
// MyAppDelegate.h
@class Reachability;
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
Reachability *hostReach;
}
@end
// MyAppDelegate.m
- (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:@"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];
// ...
}