アプリが「バックグラウンドモード」から戻ったことをどのように検出できますか?つまり、ユーザーが「ホームボタン」を押したときにアプリがデータを(60秒ごとに)フェッチしたくないということです。ただし、アプリが初めてフォアグラウンドモードになったときに、「特別な」更新を行いたいと思います。
これらの2つのイベントを検出するにはどうすればよいですか。
- アプリがバックグラウンドモードに移行
- アプリがフォアグラウンドモードになります
前もって感謝します。
フランソワ
アプリが「バックグラウンドモード」から戻ったことをどのように検出できますか?つまり、ユーザーが「ホームボタン」を押したときにアプリがデータを(60秒ごとに)フェッチしたくないということです。ただし、アプリが初めてフォアグラウンドモードになったときに、「特別な」更新を行いたいと思います。
これらの2つのイベントを検出するにはどうすればよいですか。
前もって感謝します。
フランソワ
このようなイベントをリッスンする方法は次のとおりです。
// 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)
チェックは冗長になりました(何らかの理由でiOS 3を本当にサポートする必要がある場合を除く)。ただし、APIを使用する前に、APIが存在するかどうかを確認するためのこの手法を知っておくと便利です。どのOSバージョンにどのAPIが存在するかについての外部の知識を使用するのではなく、特定のAPIが存在するかどうかをチェックするため、OSバージョンをテストするよりもこの手法の方が好きです。
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を参照してください。