2012-06-24 188 views
1

我已經創建了一個iPhone應用程序,我想檢查互聯網connectivity.At應用程序的委託方法我寫互聯網檢查iOS應用程序

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; 
    viewController1 = [[ViewController1 alloc] initWithNibName:@"ViewController1" title:firstTabTitleGlobal bundle:nil]; 
    viewController2 = [[ViewController2 alloc] initWithNibName:@"ViewController2" title:secondTabTitleGlobal bundle:nil]; 

    newNavController = [[UINavigationController alloc] initWithRootViewController:viewController1]; 

    userNavController = [[UINavigationController alloc] initWithRootViewController:viewController2]; 

    self.tabBarController = [[[UITabBarController alloc] init] autorelease]; 
    self.tabBarController.viewControllers = [NSArray arrayWithObjects:newNavController,userNavController,nil] 

    Reachability *r = [Reachability reachabilityWithHostName:globalHostName]; 

    NetworkStatus internetStatus = [r currentReachabilityStatus]; 

    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) 
    { 
     [self showAlert:globalNetAlertTitle msg:globalNetAlertMsg]; 
     [activityIndicator stopAnimating]; 
    } 
    else 
    { 
     [activityIndicator stopAnimating]; 
     self.window.rootViewController = self.tabBarController; 
     [self.window makeKeyAndVisible]; 
    } 
} 

我的代碼是確定的didFinishLaunchingWithOptions方法,因爲在沒有互聯網連接,然後放映alert.But問題是沒有interner然後default.png顯示。當我再次運行應用程序時,應用程序將從顯示default.png運行。沒有發生。 在此先感謝。

回答

2

application:didFinishLaunchingWithOptions:只會在應用程序啓動時運行。

如果你希望你的應用程序檢查可用性在隨後的應用程序激活,嘗試把你的代碼applicationDidBecomeActive:

+2

我認爲你的答案修復設置了由提問者的問題 - 對了投票的原因,但使用NSNotifications在提供動態更新,而不必手動檢查互聯網更加實用和有用連接。 –

1

什麼可能是更好的使用NSNotifications是,動態地告訴你,如果你有連接。你可以用一個叫做'reachabilty'的蘋果類來做到這一點。一旦你將文件包含在你的項目中,你就可以使用類似的東西;

//in viewDidOnload  
[[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(handleNetworkChange:) 
              name:kReachabilityChangedNotification object:nil]; 
reachability = [[Reachability reachabilityForInternetConnection] retain]; 
[reachability startNotifier]; 
NetworkStatus status = [reachability currentReachabilityStatus]; 

if (status == NotReachable) { 
    //Do something offline 
} else { 
    //Do sometihng on line 
} 

- (void)handleNetworkChange:(NSNotification *)notice{ 
NetworkStatus status = [reachability currentReachabilityStatus]; 
if (status == NotReachable) { 
    //Show offline image 
} else { 
    //Hide offline image 
} 

} 

(這是從Reachability network change event not firing更正後的代碼)

然後,您就可以儘快的任何網絡變化發生更新您的圖像。但是,不要忘記刪除自己接收dealloc中的通知;

[[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil]; 

如果您需要更多關於如何實現這一點的信息,我會很樂意提供幫助!

喬納森