2012-06-24 144 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]; 

如果您需要更多关于如何实现这一点的信息,我会很乐意提供帮助!

乔纳森