You should be using app lifecycle events (SceneDelegate/AppDelegate), not view controller lifecycle events (viewDidLoad
, viewDidAppear
, etc). sceneDidBecomeActive(_:)
should be fine for your purposes — for iOS 13+, you should be using SceneDelegate
to listen to scene phases, like going to settings (becoming inactive) and then coming back (becoming active again).
/// SceneDelegate.swift
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
/// your code here
}
If you want to listen to sceneDidBecomeActive
directly in your view controller, try listening to the didActivateNotification
notification.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver( /// add observer
self,
selector: #selector(activated),
name: UIScene.didActivateNotification,
object: nil
)
}
@objc func activated() {
print("View controller is back now")
}
}