What's the best way to detect when the app is entering the background for my view?
You can have any class interested in when the app goes into the background receive notifications. This is a good alternative to coupling these classes with the AppDelegate.
When initializing said classes:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];
Responding to the notifications
-(void)appWillResignActive:(NSNotification*)note
{
}
-(void)appWillTerminate:(NSNotification*)note
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
}
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 to detect when an Android app goes to the background and come back to the foreground
The onPause()
and onResume()
methods are called when the application is brought to the background and into the foreground again. However, they are also called when the application is started for the first time and before it is killed. You can read more in Activity.
There isn't any direct approach to get the application status while in the background or foreground, but even I have faced this issue and found the solution with onWindowFocusChanged
and onStop
.
For more details check here Android: Solution to detect when an Android app goes to the background and come back to the foreground without getRunningTasks or getRunningAppProcesses.
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 when a view controller goes to background and gets resumed
use UIApplicationDidBecomeActive
for resume and UIApplicationWillResignActive
for handle goes background
SwiftUI
Text("check application state!")
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
print("User received on willResignActiveNotification!")
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
print("User received on didBecomeActiveNotification!")
}
Swift 5.x > above
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.openAndCloseActivity), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.openAndCloseActivity), name: UIApplication.didBecomeActiveNotification, object: nil)
}
@objc func openAndCloseActivity(_ notification: Notification) {
if notification.name == UIApplication.didBecomeActiveNotification{
// become active notifictaion
}else{
// willResignActiveNotification
}
}
Swift 5.x < below
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.closeActivityController), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.openactivity), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
and handle the method as
func closeActivityController() {
}
func openactivity() {
//view should reload the data.
}
other notification types are
extension NSNotification.Name {
@available(iOS 4.0, *)
public static let UIApplicationDidEnterBackground: NSNotification.Name
@available(iOS 4.0, *)
public static let UIApplicationWillEnterForeground: NSNotification.Name
public static let UIApplicationDidFinishLaunching: NSNotification.Name
public static let UIApplicationDidBecomeActive: NSNotification.Name
public static let UIApplicationWillResignActive: NSNotification.Name
public static let UIApplicationDidReceiveMemoryWarning: NSNotification.Name
public static let UIApplicationWillTerminate: NSNotification.Name
}
swift - How to detect from what ViewController application enter background?
On AppDelegate Methods: applicationDidEnterBackground
or applicationWillEnterForeground
, you can get the top most UIViewController. It is well explained on this question: Get top most UIViewController
Related Topics
Using Custom Fonts in Wkwebview
Undocumented Nsurlerrordomain Error Codes (-1001, -1003 and -1004) Using Storekit
How to Export "Fat" Cocoa Touch Framework (For Simulator and Device)
How to Determine Whether Code Is Running in Debug/Release Build
Error: "The Sandbox Is Not in Sync with the Podfile.Lock..." After Installing Restkit with Cocoapods
How to Build For Armv6 and Armv7 Architectures With iOS 5
Displaying a Stock iOS Notification Banner When Your App Is Open and in the Foreground
Best Way to Check If Uitableviewcell Is Completely Visible
How to Make a Push Segue When a Uitableviewcell Is Selected
Firebasestorage: How to Delete Directory
Cut Transparent Hole in Uiview
Add an Element to an Array in Swift