gpt4 book ai didi

ios - 单击主页按钮后未调用 viewWillAppear

转载 作者:搜寻专家 更新时间:2023-10-31 22:14:29 26 4
gpt4 key购买 nike

我有这个 View Controller

class ViewController: UIViewController {


override func viewWillAppear(animated: Bool) {
let user = NSUserDefaults()
let mobileNumber = user.valueForKey("mobileNumber") as? String
if let mobileNumber = mobileNumber {
print("mobile number = \(mobileNumber)")
}else {
print("no mobile number")
}
}


@IBAction func makePhoneCall(sender: UIButton) {
if let phoneCall = phoneCall {
let user = NSUserDefaults()
user.setValue(phoneCall, forKey: "mobileNumber")

当用户点击按钮时,我将 mobileNumber 保存在 nsuserdefault 中。

然后我点击按钮,然后我再次打开应用程序,但问题是当我再次打开应用程序时,我没有打赌来自 viewWillAppear 的任何消息,即使我正在打印ifelse 部分。

最佳答案

tylersimko 是正确的,当应用程序进入前台时,viewWillAppear(_:) 不会被调用,而该事件会被“应用程序将进入后台”捕获。

也就是说,您不需要从应用委托(delegate)中观察到这一点,而是可以使用 UIApplicationWillEnterForegroundNotification notification :

override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidEnterForeground", name: UIApplicationWillEnterForegroundNotification, object: nil)
}

func applicationDidEnterForeground() {
// Update variable here.
}

deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}

上面的代码:

  1. 当您的 View 加载时,您的 View Controller 注册为在应用程序进入前台时调用函数 applicationDidEnterForeground()
  2. 函数 applicationDidEnterForeground() 会做任何需要做的事情。
  3. View Controller 在取消分配时取消注册所有通知,以避免在 9.0 之前的 iOS 版本中出现僵尸引用。

鉴于您正在使用 NSUserDefaults,您可以考虑观察 NSUserDefaultsDidChangeNotification

关于ios - 单击主页按钮后未调用 viewWillAppear,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33662102/

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