1. 程式人生 > >[iOS] How to detect when iOS app appears in foreground, with Swift?

[iOS] How to detect when iOS app appears in foreground, with Swift?

You can use the applicationDidBecomeActive(_:) method of your UIApplicationDelegate. You should read up on the app lifecycle. Your app delegate would then need to inform your view controller in some fashion.

Or you can register your view controller as an observer of the UIApplicationDidBecomeActivenotification. Documentation for that can be found 

here

if (viewController.isViewLoaded && viewController.view.window) {
    // viewController is visible
}

Or if you have a UINavigationController managing the view controllers, you could check its visibleViewController property instead.

Also, in Swift on iOS 9 (or later):

if viewController.viewIfLoaded
?.window != nil { // viewController is visible }