Detect iOS app entering background
Asked Answered
M

7

55

I'm working on a game for iOS coded in Swift. I've tried to find a way to detect when the app enters background mode or is interrupted for other reasons, for example a phone call but can't find anything. How do I do it?

Melanymelaphyre answered 12/1, 2016 at 13:18 Comment(3)
Try looking in your application delegate.Equidistant
See documentation for UIApplicationDelegate.Pocahontas
Does this answer your question? What's the best way to detect when the app is entering the background for my view?Hockey
C
84

You can add an observer to your view controller:

edit/update: Xcode 11 • Swift 5

iOS13 or later

UIScene.willDeactivateNotification

iOS12 or earlier

UIApplication.willResignActiveNotification

if #available(iOS 13.0, *) {
    NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIScene.willDeactivateNotification, object: nil)
} else {
    NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIApplication.willResignActiveNotification, object: nil)
}

and add a selector method to your view controller that will be executed when your app receives that notification:

@objc func willResignActive(_ notification: Notification) {
    // code to execute
}
Cerumen answered 12/1, 2016 at 13:59 Comment(6)
Thanks! For Swift 4, add @objc before func.Khoisan
For Swift 4.2, use name: UIApplication.willResignActiveNotification.Littman
this method can be triggered if u receive an SMS too . developer.apple.com/documentation/uikit/uiapplicationdelegate/… . the method is actually didEnterBackgroundNotificationHomophonic
It should be noted that this no longer works for apps under iOS 13 unless the app has opted out of using scenes.Sonometer
@Sonometer If so can you please suggest how it should be tackled ? Do I need Xcode 11 for the same ?Frication
@SharadChauhan See #57488557Sonometer
K
34

In swift 5.x: To observe app enters background event, add this code to your viewDidLoad() method.

    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)

    @objc func appMovedToBackground() {
        // do whatever event you want
    }

you have to use UIApplication.didEnterBackgroundNotification. If you want to observe if app came to foreground event, use UIApplication.willEnterForegroundNotification

So, the full code will be:

override func viewDidLoad() {
    super.viewDidLoad()

    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
    
    notificationCenter.addObserver(self, selector: #selector(appCameToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    
    // Do any additional setup after loading the view.
}
 @objc func appMovedToBackground() {
    print("app enters background")
}

@objc func appCameToForeground() {
    print("app enters foreground")
}
Klinges answered 5/2, 2019 at 11:51 Comment(1)
It should be noted that this no longer works for apps under iOS 13 unless the app has opted out of using scenes.Sonometer
P
9

Swift3

let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationWillResignActive, object: nil)


func appMovedToBackground() {
    print("App moved to background!")
}
Peritonitis answered 14/12, 2016 at 10:36 Comment(1)
It should be noted that this no longer works for apps under iOS 13 unless the app has opted out of using scenes.Sonometer
L
7

To detect the app enters background, you can check in the appDelegate.m find the application delegate method

applicationDidEnterBackground

This method will get called, once the app enters background.

Legend answered 12/1, 2016 at 13:21 Comment(3)
This would only tell you when the app had already entered the background - there would be some latency between this happening, and the method being called.Fates
Yes, exactly applicationWillResignActive possible answer, +1 @AlexBlundell : Good work.Legend
It should be noted that this no longer works for apps under iOS 13 unless the app has opted out of using scenes.Sonometer
A
7

SwiftUI

From background

Text("Hello, World!")
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
    print("To the foreground!")
}

To the background

Text("Hello, World!")
    .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
        print("To the background!")
    }
Archibald answered 19/1, 2020 at 7:21 Comment(1)
UIApplication.willResignActiveNotification is not appropriate for app entering background. It can trigger even when you receive phone call.Star
S
4

For SwiftUI you can use:

YourView()
 .onReceive(NotificationCenter.default.publisher(for: UIScene.willDeactivateNotification)) { _ in
     //...
 }
Squamosal answered 2/1, 2021 at 23:13 Comment(1)
This is a great answer, you know how can i keep my download when app in background?Pushbike
F
1

Take a look at the delegate methods defined in your instance of UIApplicationDeletegate (called AppDelegate.m by default). Specifically the following would be useful:

- (void)applicationWillResignActive:(UIApplication *)application

This method is called to let your app know that it is about to move from the active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the app and it begins the transition to the background state. An app in the inactive state continues to run but does not dispatch incoming events to responders.

Taken from the Apple Documentation - here

Fates answered 12/1, 2016 at 13:22 Comment(1)
It should be noted that this no longer works for apps under iOS 13 unless the app has opted out of using scenes.Sonometer

© 2022 - 2024 — McMap. All rights reserved.