web-dev-qa-db-ja.com

iphone 4 sdk:バックグラウンドモードからの復帰を検出

アプリが「バックグラウンドモード」から戻ったことをどのように検出できますか?つまり、ユーザーが「ホームボタン」を押したときにアプリがデータを(60秒ごとに)フェッチすることを望まないのです。ただし、アプリが初めてフォアグラウンドモードになったときに、「特別な」更新を行いたいと思います。

これらの2つのイベントを検出するにはどうすればよいですか。

  1. アプリがバックグラウンドモードに移行
  2. アプリがフォアグラウンドモードになります

前もって感謝します。

フランソワ

26
Francois

このようなイベントをリッスンする方法は次のとおりです。

_// Register for notification when the app shuts down
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationWillTerminateNotification object:nil];

// On iOS 4.0+ only, listen for background notification
if(&UIApplicationDidEnterBackgroundNotification != nil)
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationDidEnterBackgroundNotification object:nil];
}

// On iOS 4.0+ only, listen for foreground notification
if(&UIApplicationWillEnterForegroundNotification != nil)
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationWillEnterForegroundNotification object:nil];
}
_

注:if(&SomeSymbol)チェックは、コードがiOS4.0以降およびiOS3.xでも機能することを確認します-iOS4.xまたは5.xSDKに対してビルドし、展開ターゲットをiOSに設定した場合3.xアプリは引き続き3.xデバイスで実行できますが、関連するシンボルのアドレスはnilになるため、3.xデバイスに存在しない通知を要求しようとはしません(アプリがクラッシュする可能性があります) )。

更新:この場合、if(&Symbol)チェックは冗長になりました(あなた本当にがサポートする必要がない限り)何らかの理由でiOS3)。ただし、APIを使用する前に、APIが存在するかどうかを確認するためのこの手法を知っておくと便利です。どのOSバージョンにどのAPIが存在するかについての外部の知識を使用するのではなく、特定のAPIが存在するかどうかを確認するため、OSバージョンをテストするよりもこの手法を好みます。

48
jhabbott

UIApplicationDelegateを実装する場合は、デリゲートの一部として関数にフックすることもできます。

- (void)applicationDidEnterBackground:(UIApplication *)application {
   /*
   Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
 If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
   */
    NSLog(@"Application moving to background");
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
  /*
   Called as part of the transition from the background to the active state: here you can undo many of the changes made on entering the background.
   */
    NSLog(@"Application going active");
}

プロトコルリファレンスについては、 http://developer.Apple.com/library/ios/#documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html を参照してください。

5
Chris R