Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if the application in background or foreground in swift

is there any way to know the state of my application if it is in background mode or in foreground . Thanks

like image 568
Mohammed Aboelwafa Avatar asked Aug 16 '16 10:08

Mohammed Aboelwafa


People also ask

How do I know if an app is in the background or foreground iOS?

To detect if an iOS application is in background or foreground we can simply use the UIApplication just like we can use it to detect many other things like battery state, status etc. The shared. application state is an enum of type State, which consists of the following as per apple documentation.

How do you be notified when your Swiftui app moves to the background?

This is done using three steps: Adding a new property to watch an environment value called scenePhase . Using onChange() to watch for the scene phase changing. Responding to the new scene phase somehow.


2 Answers

[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 } 
like image 137
Anbu.Karthik Avatar answered Sep 20 '22 14:09

Anbu.Karthik


Swift 3

  let state: UIApplicationState = UIApplication.shared.applicationState              if state == .background {                  // background             }             else if state == .active {                  // foreground             } 
like image 43
dimohamdy Avatar answered Sep 19 '22 14:09

dimohamdy