因此可以在以下方法中这样写:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//检查网络
Reachability *reach = [Reachability reachabilityWithHostname:@"www.apple.com"];
NetworkStatus status = [reach currentReachabilityStatus];
[self connectInState:status];
returnYES;
}
//提示用户正在使用哪种连接方式
- (void)connectInState:(NetworkStatus)state
{
switch (state) {
//网络未连接
case NotReachable:{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络未连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:Nil,nil];
[alert dismissWithClickedButtonIndex:1 animated:NO];
[alert show];
}
break;
//正在使用WiFi连接
case ReachableViaWiFi:{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"正使用WiFi连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:Nil,nil];
[alert dismissWithClickedButtonIndex:1 animated:NO];
[alert show];
}
break;
//正在使用3G/GPRS网络连接
case ReachableViaWWAN:{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"正使用3G/GPRS网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:Nil,nil];
[alert dismissWithClickedButtonIndex:1 animated:NO];
[alert show];
}
default:
break;
}
}
三. 链接状态的实时通知
网络连接状态的实时检查,通知在网络应用中也是十分必要的。接续状态发生变化时,需要及时地通知用户:
Reachability 2.0版本
// 设置网络状态变化时的通知函数
- (void)viewDidLoad
{
[super viewDidLoad];
Reachability * reach = [Reachability reachabilityWithHostname:@"www.apple.com"];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
[reach startNotifier];
}
-(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];
// [alert release];
} else if (status == ReachableViaWiFi) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"正在使用WiFi" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
// [alert release];
}
}