gpt4 book ai didi

ios - 在不打开 ViewController 的情况下订阅 NotificationCenter

转载 作者:行者123 更新时间:2023-11-28 07:56:33 25 4
gpt4 key购买 nike

我正在从 UITabBarController 中的第一个 viewController 向 UITabBarController 中的第二个 viewController 发送通知,但第二个 viewController 似乎没有观察或收听通知直到我打开它....所以基本上我必须打开第二个 viewController 来订阅通知然后返回到第一个发送它....我如何解决这个问题以便通知到达secondViewController 无需打开订阅

最佳答案

在SecondViewController中做一个通知接收函数

 @objc func notified(_ noti : Notification)  {
print("Recieved fired noti")
}

为您的 UITabbarController 创建一个自定义类。在 Tabbarcontroller 类的 viewDidLoad 中写下这些行

let vc = self.viewControllers![1] as! SecondViewController
NotificationCenter.default.addObserver(vc, selector: #selector(vc.notified(_:)), name: NSNotification.Name(rawValue: "NotificationSample"), object: nil)

这里我以索引 1 为例,将其替换为 tabbarController 中的 secondViewController 索引。

然后从任何你想要的地方发布你的通知,例如,从 FirstviewController

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NotificationSample"), object: nil)

在最好的情况下,这应该有效。

关于ios - 在不打开 ViewController 的情况下订阅 NotificationCenter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47885896/

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