1

インターネット接続を確認したいiPhoneアプリケーションを作成しました。私が書いたアプリデリゲートメソッドのdidFinishLaunchingWithOptionsメソッドで

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

インターネット接続がない場合にアラートが表示されるため、私のコードは問題ありません。アプリを再度実行すると、表示されている default.png からアプリが実行されます。そして、何も起こりません。前もって感謝します。

4

3 に答える 3

2

application:didFinishLaunchingWithOptions:アプリの起動時にのみ実行されます。

アプリケーションがその後のアプリケーションのアクティブ化で可用性をチェックするようにしたい場合は、コードを入れてみてください。applicationDidBecomeActive:

于 2012-06-24T07:06:58.150 に答える
1

より良いのは、接続があるかどうかを動的に通知するために NSNotifications を使用することです。これは、'reachabilty' と呼ばれる Apple クラスで行うことができます。プロジェクトにファイルを含めたら、次のようなものを使用できます。

//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
 }

}

(これは、到達可能性ネットワークの変更イベントが発生しないからの修正されたコードです)

これにより、ネットワークの変更が発生するとすぐにイメージを更新できるようになります。ただし、dealloc with で通知を受け取らないようにすることを忘れないでください。

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

これを実装する方法についてさらに情報が必要な場合は、喜んでお手伝いします。

ジョナサン

于 2012-06-24T16:04:01.943 に答える