从 AppDelegate 通知视图控制器的正确方法是什么? [英] What is correct way to notify view controller from AppDelegate?

查看:46
本文介绍了从 AppDelegate 通知视图控制器的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I registered my application to open specific file type (cvs in my case). So when user touches "Open in -> My App"

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

函数被触发.在这个函数中,我从文件读取数据到本地数组.在我的视图控制器中,我需要显示以上数据.那么,通知 VC 收到数据并将数据传递给它的正确方法是什么?

function is triggered. In this function I read data from file to local array. In my View Controller I need to display above data. So what is correct way to notify VC that data were received and pass data to it?

推荐答案

您需要像这样发布通知:

You need to post a notification like this:

常量文件中的某处:

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

在 AppDelegate 中:

In AppDelegate:

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

在 ViewController 的 viewDidLoad 中:

In ViewController's viewDidLoad:

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

视图控制器中的回调:

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

这篇关于从 AppDelegate 通知视图控制器的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆