アプリのライフサイクル
一般論の iOS における具体。
状態#
Not running
↓ 起動
Inactive(遷移中、通知が出ているとき)
↓
Active(前面、イベントを受け取る)
↓ ホーム画面へ
Background(数秒〜。タスクを申請すれば延長)
↓
Suspended(メモリ上にあるが実行されない)
↓ メモリ不足
Terminated(**通知なしで終了されうる**)重要な性質#
Suspended からの終了は通知されない。
applicationWillTerminate は
Suspended 状態から終了される場合には呼ばれない。
つまり当てにできない。
保存すべきタイミング = Background に移った瞬間SwiftUI では `Environment(\.scenePhase) で観測する。
swift
(\.scenePhase) private var phase
.onChange(of: phase) { _, new in
if new == .background { save() }
}Background での猶予#
背景に移ってから通常数秒で Suspended になる。
延長したい場合は
beginBackgroundTask で申請する(おおむね 30 秒程度)。
長時間の処理は 専用の仕組みを使う。
メモリ警告#
didReceiveMemoryWarning / .memoryWarning 通知キャッシュを解放する。 応じないと強制終了される可能性が高まる。
Suspended 状態のアプリは、 メモリ不足時に優先的に終了される。 使用メモリが少ないほど、 復帰時に前の状態が残っている確率が上がる。
参考文献#
- Apple. Managing your app's life cycle. https://developer.apple.com/documentation/uikit/managing-your-app-s-life-cycle
- Apple. ScenePhase — SwiftUI. https://developer.apple.com/documentation/swiftui/scenephase