class ViewController: UIViewController {
var check=UIApplication.didEnterBackgroundNotification{
didSet{
print("print some thing")
}
}
override func viewDidLoad() {
super.viewDidLoad()
}}
I run this code in my iPhone, when I enter background it is not executing the printing
Where is wrong
Your code is in right way of declaring of any variable with a class type.
However, there is big mistake by creating the instance of UIApplication.didEnterBackgroundNotification
which is class
type and is subclassed by NSNotification.Name
which is a struct
.
When you are accessing the check
variable you can't set it because its non mutable struct means you can't mutate it (assigning value to it). So, the property observer didSet
is not going to call, hence the print also not going call. This is the mistake.
Solution:
We can use NotificationCenter
to observe the transitions of foreground to background and vice versa of the iOS
application.
From Apple Doc.s
Objects register with a notification center to receive notifications (NSNotification objects) using the addObserver(_:selector:name:object:) or addObserver(forName:object:queue:using:) methods. When an object adds itself as an observer, it specifies which notifications it should receive. An object may therefore call this method several times in order to register itself as an observer for several different notifications.
Each running app has a default notification center, and you can create new notification centers to organize communications in particular contexts.
Try this
For Foreground
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterForeground), name: UIApplication.didBecomeActiveNotification, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
}
@objc private func applicationDidEnterForeground() {
//Do your stuff here
}
For Background
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
}
@objc private func applicationDidEnterBackground() {
//Do your stuff here
}
For more, please visit
https://developer.apple.com/documentation/foundation/notificationcenter