標籤:
iOS 斷網處理 (2014-01-13 18:13:21)
轉載▼
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
//開啟網路狀況的監聽
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ;
[self.hostReach startNotifier]; //開始監聽,會啟動一個run loop
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
//網路連結改變時會調用的方法
-(void)reachabilityChanged:(NSNotification *)note
{
Reachability *currReach = [note object];
NSParameterAssert([currReach isKindOfClass:[Reachability class]]);
//對串連改變做出響應處理動作
NetworkStatus status = [currReach currentReachabilityStatus];
//如果沒有串連到網路就彈出提醒實況
self.isReachable = YES;
if(status == NotReachable)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網路連接異常" message:@"暫無法訪問書城資訊" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
[alert show];
[alert release];
self.isReachable = NO;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網路連接資訊" message:@"網路連接正常" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
[alert show];
[alert release];
self.isReachable = YES;
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
//開啟網路狀況的監聽
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ;
[self.hostReach startNotifier]; //開始監聽,會啟動一個run loop
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
//網路連結改變時會調用的方法
-(void)reachabilityChanged:(NSNotification *)note
{
Reachability *currReach = [note object];
NSParameterAssert([currReach isKindOfClass:[Reachability class]]);
//對串連改變做出響應處理動作
NetworkStatus status = [currReach currentReachabilityStatus];
//如果沒有串連到網路就彈出提醒實況
self.isReachable = YES;
if(status == NotReachable)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網路連接異常" message:@"暫無法訪問書城資訊" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
[alert show];
[alert release];
self.isReachable = NO;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網路連接資訊" message:@"網路連接正常" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
[alert show];
[alert release];
self.isReachable = YES;
}
}
通過如上代碼,在應用程式的任何一個介面都可以使用下面的單例來判斷網路是否串連
[cpp] view plaincopyprint?
AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if(appDlg.isReachable)
{
NSLog(@"網路已串連");//執行網路正常時的代碼
}
else
{
NSLog(@"網路連接異常");//執行網路異常時的代碼
}
iOS 斷網處理