观察者在使用 Uiapplication() 时遇到问题

Problem with observers while engaging them with Uiapplication()

class ViewController: UIViewController {
var check=UIApplication.didEnterBackgroundNotification{


    didSet{

        print("print some thing")
    }
}

override func viewDidLoad() {
    super.viewDidLoad()


 }}

我运行这段代码在我的iPhone中,当我进入后台时它没有执行打印

哪里错了

您的代码以正确的方式声明任何具有 class 类型的变量。

但是,创建 UIApplication.didEnterBackgroundNotification 的实例是一个很大的错误,它是 class 类型并且被 NSNotification.Name 子class 编辑,struct =].

当您访问 check 变量时,您不能设置它,因为它的非可变结构意味着您不能改变它(为其赋值)。因此,属性 观察者 didSet 不会调用,因此打印也不会调用。这是错误的。

解法:

我们可以使用 NotificationCenter 来观察 iOS 应用程序前景到背景的过渡,反之亦然。

来自苹果 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.

试试这个

前景

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