たのしい人生

iOS アプリでマルチタスク切り替え画面に入ったことを検出する話

小ネタです。アプリがアクティブなときに、マルチタスク切り替え画面(ホームキー二連打)に入ったことを検出したい。

結論

マルチタスク切り替えそのもの画面に入ったことそのものは検出できないが、マルチタスク切り替え画面に入るとアプリケーションは Inactive になるので、たとえば UIApplicationWillResignActive を購読しておけばそれで検出できる。通知センターやコントロールセンターを開いた場合もアプリケーションは Inactive になるので厳密な見分けが必要な場合はもう少し考えなければいけないかも。

iOS アプリのライフサイクル

アプリにまつわるイベントであると考えられるので、 Execution States for Apps を見ましょう。これは散々引用されてますしみなさん一度は見たことがあると思います。

State Description
Not running The app has not been launched or was running but was terminated by the system.
Inactive The app is running in the foreground but is currently not receiving events. (It may be executing other code though.) An app usually stays in this state only briefly as it transitions to a different state.
Active The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.
Background The app is in the background and executing code. Most apps enter this state briefly on their way to being suspended. However, an app that requests extra execution time may remain in this state for a period of time. In addition, an app being launched directly into the background enters this state instead of the inactive state. For information about how to execute code while in the background, see Background Execution.
Suspended The app is in the background but is not executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, an app remains in memory but does not execute any code. When a low-memory condition occurs, the system may purge suspended apps without notice to make more space for the foreground app.

Inactive

アプリケーションライフサイクルのイメージとしては

Not running
 ↓
Inactive
 ↓
Active
 ↓↑
Inactive
 ↓↑
Background

ではないかと思います。 Notification で UIApplicationDidEnterBackground はよく使うと思いますが、 UIApplicationWillResignActive は通り過ぎるだけでなにに使うんだ...?

Inactive の説明を読んでみると

The app is running in the foreground but is currently not receiving events. (It may be executing other code though.) An app usually stays in this state only briefly as it transitions to a different state.

アプリケーションは通常、状態遷移する一瞬この状態になると言っています。やっぱり通過するだけ?

フォアグラウンドだけど UI イベントだけ受け取らない状態

Inactive の説明の前半にはこうも書いてあります。Inactive なアプリケーションはフォアグラウンドにいるけれど UI イベントは受け取らないよ。

よくよく考えると マルチタスク切り替え画面 はまさにこの状態に当てはまります。 エスパーじゃないと気づけないと思うんですが。

さらによくよく考えると、マルチタスク切り替え画面以外にもアプリケーションはフォアグラウンドだけれど UI イベントを取らない状態があります。通知センターコントロールセンター を開いた時もこの状態になります。よく出来てますね。でも遷移中一瞬なる状態だよって説明は消したほうがいいと思う。

というわけで、アプリケーションの状態が Inactive になる時を見ていればほぼ目的は達成できそうです。

おしまい。

Amazon.co.jpアソシエイト