从AppDelegate通知视图控制器的正确方法是什么?

lig*_*ght 2 model-view-controller ios swift

我注册了应用程序以打开特定的文件类型(以我的情况为cvs)。因此,当用户触摸“在-打开->我的应用中打开”时

application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:])
Run Code Online (Sandbox Code Playgroud)

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

ale*_*nik 6

您需要发布这样的通知:

在您的Constants文件中的某个位置:

extension Notification.Name {
    public static let myNotificationKey = Notification.Name(rawValue: "myNotificationKey")
}
Run Code Online (Sandbox Code Playgroud)

在AppDelegate中:

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

在ViewController的viewDidLoad中:

NotificationCenter.default.addObserver(self, selector: #selector(self.notificationReceived(_:)), name: Notification.Name.myNotificationKey, object: nil)
Run Code Online (Sandbox Code Playgroud)

视图控制器中的回调:

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