gpt4 book ai didi

ios - 从 AppDelegate 通知 View Controller 的正确方法是什么?

转载 作者:可可西里 更新时间:2023-10-31 23:58:53 26 4
gpt4 key购买 nike

我注册了我的应用程序以打开特定文件类型(在我的例子中是 cvs)。因此,当用户触摸“打开方式 -> 我的应用程序”

application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:])

函数被触发。在此函数中,我将数据从文件读取到本地数组。在我的 View Controller 中,我需要显示以上数据。那么通知 VC 接收到数据并将数据传递给它的正确方法是什么?

最佳答案

您需要发布这样的通知:

常量文件中的某处:

extension Notification.Name {
public static let myNotificationKey = Notification.Name(rawValue: "myNotificationKey")
}

在 AppDelegate 中:

let userInfo = [ "text" : "test" ] //optional
NotificationCenter.default.post(name: .myNotificationKey, object: nil, userInfo: userInfo)

在 ViewController 的 viewDidLoad 中:

NotificationCenter.default.addObserver(self, selector: #selector(self.notificationReceived(_:)), name: Notification.Name.myNotificationKey, object: nil)

View Controller 中的回调:

func notificationReceived(_ notification: Notification) {
//getting some data from userInfo is optional
guard let text = notification.userInfo?["text"] as? String else { return }
//your code here
}

关于ios - 从 AppDelegate 通知 View Controller 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165443/

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