我想在点击通知打开应用程序时调用onDidReceiveNotification
函数。 (ViewController
是第一个 View Controller , Root View Controller )
当应用程序打开或在后台时,它工作正常,但是当应用程序未打开或在后台(不在内存中)并点击打开应用程序时,onDidReceiveNotification
函数不起作用打电话,
当使用点击推送通知打开应用程序时,我应该如何调用 onDidReceiveNotification
函数
ViewController.swift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NotificationCenter.default.removeObserver(self, name: .didReceiveAlert, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.onDidReceiveNotification(_:)), name: .didReceiveAlert, object: nil)
}
@objc func onDidReceiveNotification(_ notification:Notification) {
print("Received Notification")
}
}
AppDelegate.swift
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
NotificationCenter.default.post(name: .didReceiveAlert, object: nil)
}
最佳答案
当应用程序打开或在后台时调用NotificationCenter.defalut.post
,当应用程序终止/关闭并使用通知打开时,获取实例并通过菜单调用onDidReceiveAlert
函数,请参见以下代码。
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if application.applicationState == .background || application.applicationState == .active {
NotificationCenter.default.post(name: .didReceiveAlert, object: nil)
}else {
let nav = window?.rootViewController as! UINavigationController
let mainVC = nav.viewControllers.first as! ViewController
mainVC.onDidReceiveAlert(nil)
}
}
或者从 UINavigationController
堆栈中获取 ViewController
实例并直接调用 ViewController
的函数(不需要通知观察器)
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let nav = window?.rootViewController as! UINavigationController
let mainVC = nav.viewControllers.first as! ViewController
mainVC.onDidReceiveAlert(nil)
}
创建带有可选参数的函数,使用以下代码。
@objc func onDidReceiveAlert(_ notification:Notification? = nil) {
print("Received Notification")
}
关于ios - swift IOS : Call Specific function of UIviewController when open app from notification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54885088/