gpt4 book ai didi

iOS 前台观察器未被调用

转载 作者:行者123 更新时间:2023-11-28 23:21:34 24 4
gpt4 key购买 nike

我已经为后台和前台事件添加了一个观察者。

当双击主页按钮时,后台观察器被调用。但是当我立即选择我的应用程序时,我的前台观察器没有被调用。请检查此 gif 演示 https://raw.githubusercontent.com/billionlaughs/Demo/master/resources/foreground_issue.gif .

测试的 iOS 版本:13.1.2。

代码片段:


class ViewController: UIViewController {

@IBOutlet weak var uiLabelToShow: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Will be invoked when app goes to background
NotificationCenter.default.addObserver(self, selector: #selector(myBGObserver), name: .UIApplicationWillResignActive, object: nil)
//Will be invoked when app goes to foreground
NotificationCenter.default.addObserver(self, selector: #selector(myFGObserver), name: .UIApplicationWillEnterForeground, object: nil)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@objc func myBGObserver(){
uiLabelToShow.text = "Background";
}
@objc func myFGObserver(){
uiLabelToShow.text = "Foreground";
}
}

我的演示项目的 Github 链接:https://github.com/billionlaughs/Demo

我找不到解决此问题的方法/原因。请引导我走上正确的道路。

最佳答案

UIApplicationWillEnterForeground 当您的应用程序在您单击主页按钮两次后隐藏某些方式时调用(不会保持显示为您的 gif),您需要使用 UIApplicationDidBecomeActiveUIApplicationWillEnterForeground

drawBack : initially text will contain Foreground

解决做

class ViewController: UIViewController {

@IBOutlet weak var uiLabelToShow: UILabel!
var once = true
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Will be invoked when app goes to background
NotificationCenter.default.addObserver(self, selector: #selector(myBGObserver), name: .UIApplicationWillResignActive, object: nil)
//Will be invoked when app goes to foreground
NotificationCenter.default.addObserver(self, selector: #selector(myFGObserver), name: .UIApplicationDidBecomeActive, object: nil)

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@objc func myBGObserver(){
uiLabelToShow.text = "Background";
}
@objc func myFGObserver(){
uiLabelToShow.text = once ? "Normal" : "Foreground";
once = false
}
}

关于iOS 前台观察器未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59601466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com