How to Check If iOS App Is in Background

Detect if the application in background or foreground in swift

[UIApplication sharedApplication].applicationState will return current state of applications such as:

  • UIApplicationStateActive
  • UIApplicationStateInactive
  • UIApplicationStateBackground

or if you want to access via notification see UIApplicationDidBecomeActiveNotification

Swift 3+

let state = UIApplication.shared.applicationState
if state == .background || state == .inactive {
// background
} else if state == .active {
// foreground
}

switch UIApplication.shared.applicationState {
case .background, .inactive:
// background
case .active:
// foreground
default:
break
}

Objective C

UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive) {
// background
} else if (state == UIApplicationStateActive) {
// foreground
}

Detect iOS app entering background

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
}

How can I detect when the swift application is foreground from the background?

You probably need willEnterForegroundNotification.

Posted shortly before an app leaves the background state on its way to
becoming the active app.

Keep in mind thow that this notification posted olso after application(_:didFinishLaunchingWithOptions:) when opening the application for the first time.

When application opens for the first time the applicationState is inactive and when the application comes from the background the applicationState is background.

So, your code will be something like this:

token = NotificationCenter.default.addObserver(
forName: UIApplication.willEnterForegroundNotification,
object: nil,
queue: .main
) { (notification: Notification) in
if UIApplication.shared.applicationState == .background {
// Came from the background
}
}


Related Topics



Leave a reply



Submit