迅速
簡潔な答え
NotificationCenter
ではなくオブザーバーを使用してくださいviewWillAppear
。
override func viewDidLoad() {
super.viewDidLoad()
// set observer for UIApplication.willEnterForegroundNotification
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
// my selector that was defined above
@objc func willEnterForeground() {
// do stuff
}
長い答え
アプリがバックグラウンドからいつ戻ってくるかを調べるには、NotificationCenter
ではなくオブザーバーを使用しviewWillAppear
ます。これは、どのイベントがいつ発生するかを示すサンプル プロジェクトです。(これは、この Objective-C answerの適応です。)
import UIKit
class ViewController: UIViewController {
// MARK: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
print("view did load")
// add notification observers
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
print("view will appear")
}
override func viewDidAppear(_ animated: Bool) {
print("view did appear")
}
// MARK: - Notification oberserver methods
@objc func didBecomeActive() {
print("did become active")
}
@objc func willEnterForeground() {
print("will enter foreground")
}
}
アプリを最初に起動したときの出力順序は次のとおりです。
view did load
view will appear
did become active
view did appear
ホームボタンを押してからアプリをフォアグラウンドに戻した後の出力順序は次のとおりです。
will enter foreground
did become active
したがって、最初に使用しようとしていた場合は、おそらくviewWillAppear
それが必要です。UIApplication.willEnterForegroundNotification
ノート
iOS 9 以降では、オブザーバーを削除する必要はありません。ドキュメントには次のように記載されています。
dealloc
アプリが iOS 9.0 以降または macOS 10.11 以降を対象としている場合、そのメソッドでオブザーバーを登録解除する必要はありません。