2011-06-08 119 views
0

Iam目前正在檢查互聯網連接,當我第一次啓動應用程序時,但如果我關閉應用程序並打開飛行模式,然後運行該應用程序返回其工作或它應該檢查互聯網連接,如果我失去了我的wifi,它應該說你的互聯網連接丟失或類似的東西。任何人都有適當的答案呢?Iphone Sdk在應用程序中間檢查互聯網連接?

回答

1

使用Reachability API。以下是我的一個項目的應用程序委託文件中的一些代碼。

// ivars 
Reachability* hostReach; 
Reachability* internetReach; 
Reachability* wifiReach; 

- (void) reachabilityChanged: (NSNotification*)note { 

    Reachability *curReach = (Reachability *)[note object]; 

    if ([curReach currentReachabilityStatus] == NotReachable) { 

     UIAlertView *alert = [[[UIAlertView alloc] init] autorelease]; 
     alert.title = @"No network connection?"; 
     alert.message = @"No network connection."; 
     alert.delegate = self; 
     [alert addButtonWithTitle:@"OK"]; 
     [alert show]; 

    } 

} 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  

    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil]; 

    hostReach = [[Reachability reachabilityWithHostName: @"www.test.com"] retain]; 
    [hostReach startNotifier]; 

    internetReach = [[Reachability reachabilityForInternetConnection] retain]; 
    [internetReach startNotifier]; 

    wifiReach = [[Reachability reachabilityForLocalWiFi] retain]; 
    [wifiReach startNotifier]; 

    // controller setup 
    viewController = [[CFSplashViewController alloc] init]; 

    [window addSubview:viewController.view]; 
    [window makeKeyAndVisible]; 

    return YES; 
} 

// and of course, remember to release all those resources..