監聽網絡

- (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;
    }
}

 

    AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if(appDlg.isReachable)
    {
        NSLog(@"網絡已鏈接");//執行網絡正常時的代碼
    }
    else
    {
        NSLog(@"網絡鏈接異常");//執行網絡異常時的代碼
    }
相關文章
相關標籤/搜索