class ViewController: UIViewController {
var check=UIApplication.didEnterBackgroundNotification{
didSet{
print("print some thing")
}
}
override func viewDidLoad() {
super.viewDidLoad()
}}
我在我的 iPhone 中运行这段代码,当我进入后台时它没有执行打印
最佳答案
哪里不对
您的代码以正确的方式声明任何具有类类型的变量。
但是,创建 UIApplication.didEnterBackgroundNotification
的实例是一个很大的错误,它是 class
类型并且被 NSNotification.Name
子类化,它是是一个结构
。
当您访问 check
变量时,您不能设置它,因为它的非可变结构意味着您不能改变它(为其赋值)。因此,属性观察器 didSet
不会调用,因此打印也不会调用。这是错误的。
解决方案:
我们可以使用 NotificationCenter
来观察 iOS
应用程序从前景到背景的转换,反之亦然。
来自苹果文档
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.
试试这个
前景
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
}
背景
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
}
更多内容,请访问
https://developer.apple.com/documentation/foundation/notificationcenter
关于ios - 观察者在使用 Uiapplication() 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54553419/