【发布时间】:2019-02-26 12:00:05
【问题描述】:
我想在应用程序打开时通过点击通知调用onDidReceiveNotification 函数。 (ViewController 是第一个视图控制器,根视图控制器)
当应用程序打开或在后台运行正常,但是当应用程序未打开或在后台(不在内存中)并点击打开应用程序时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)
}
【问题讨论】:
-
我认为这是预期的行为,如果应用程序关闭,您需要检查 appdelegate 中
didFinishLaunchingWithOptions中的launchOptions方法以获取收到的通知详细信息。 -
didReceiveRemoteNotification 在应用关闭并使用通知打开时调用
-
查看
let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: Any]的应用启动远程通知 -
好的,例如我已经签入了launchOptions,我知道应用程序已使用通知打开,但是之后如何在视图控制器中调用我的函数“onDidReceiveNotification”
标签: ios swift push-notification apple-push-notifications nsnotificationcenter