[英]What is correct way to notify view controller from AppDelegate?
我注冊了我的應用程序以打開特定的文件類型(在我的情況下為cvs)。 所以當用戶觸摸“打開 - >我的應用程序”時
application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:])
功能被觸發。 在這個函數中,我從文件讀取數據到本地數組。 在我的View Controller中,我需要顯示上面的數據。 那么通知VC接收數據並將數據傳遞給它的正確方法是什么?
你需要發布這樣的通知:
在Constants文件中的某個位置:
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)
視圖控制器中的回調:
func notificationReceived(_ notification: Notification) {
//getting some data from userInfo is optional
guard let text = notification.userInfo?["text"] as? String else { return }
//your code here
}
Alex的上述答案是有效的,如果處理通知的視圖控制器恰好在通知進入時屏幕上,但通常不是。 在
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any])
您想更新徽章計數,然后檢查通知。 根據您擁有的通知類型,您可以靜默處理它(可能使用上面的Notification Center方法),也可以啟動相應的視圖控制器並將整個通知傳遞給它或只傳遞ID,並讓視圖控制器調用您的API id獲取所有細節。 您可以像通常更改視圖控制器一樣執行此操作,因此如果是導航控制器,則實例化新視圖控制器,將數據傳遞給導航控制器,然后將其推送到導航控制器。
let notificationTableViewController = UIStoryboard(name: Identifiers.Storyboard.Notification, bundle: nil).instantiateViewController(withIdentifier: String(describing: NotificationTableViewController.self)) as!
NotificationTableViewController
controller.notificationId = notificationId
rootNavigationController?.pushViewController(notificationTableViewController, animated: true)
如果您有標簽欄應用程序,則首先切換標簽。 如果您有某種自定義導航,則需要在容器類上調用適當的方法。
不需要使用通知。 你的應用程序將是一團糟。
JLRoutes可以幫到你! 請參閱github頁面中的示例。
在您的應用中定義一些URL,就像xxxDetail,xxxList和JLRoutes一樣。 當application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:])
被調用時。 你只需要調用[JLRoutes route: URL]
您也可以以相同的方式處理didReceiveRemoteNotification
。
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// get URL from userInfo
// [JLRoutes route: url];
}
讓服務器端向您發送帶有您定義的URL的userInfo。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.