Detect if the application in background or foreground in swift Detect if the application in background or foreground in swift ios ios

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.applicationStateif 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}


Swift 3

  let state: UIApplicationState = UIApplication.shared.applicationState            if state == .background {                // background            }            else if state == .active {                // foreground            }


Swift 4

let state = UIApplication.shared.applicationState        if state == .background {            print("App in Background")        }else if state == .active {            print("App in Foreground or Active")        }