gpt4 book ai didi

ios - 在特定的 viewController 中处理 PushNotifcations

转载 作者:行者123 更新时间:2023-11-29 00:39:12 25 4
gpt4 key购买 nike

当我的应用程序处于前台时,我正在尝试处理 PushNotifcation。如果刚刚激活的 ViewController 是特定的,我想重新加载它的数据。如果它处于非事件状态,我希望我的应用实例化一个特定的 viewController

这是我在 appDelegate 中的代码:

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

if userInfo["matchInfo"] != nil {

if application.applicationState == .active {

if self.window!.rootViewController is chatUebersichtTVC{
let uebersicht = self.window!.rootViewController as! chatUebersichtTVC
uebersicht.refresh()
}
else{
return
}


}
else{
print ("trying to activate")
let mainStoryBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let chat:chatUebersichtTVC = mainStoryBoard.instantiateViewController(withIdentifier: "chatUebersichtTVC") as! chatUebersichtTVC
let mainPageNav = UINavigationController(rootViewController: chat)
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = mainPageNav
}



}
else{
PFPush.handle(userInfo)

}
completionHandler(.newData)

}

我能够到达 self.window!.rootViewController is chatUebersichtTVC 行但它不会在之后执行。此外,当应用程序关闭时,它总是会打开最后打开的 Controller ,而不是特定的 chatUebersichTVC。

我做错了什么?

最佳答案

以下是使用NotificationCenter的示例代码:

首先,您必须声明通知名称。在 Swift 3 之前,我们使用字符串来实现此目的,现在它应该作为Notification.Name 的扩展来完成:

extension Notification.Name {
static let pushNotificationReceived = Notification.Name("pushNotificationReceived")
}

现在您可以在您的方法中发布通知:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {    
if userInfo["matchInfo"] != nil {
if application.applicationState == .active {
NotificationCenter.default.post(name: Notification.Name.pushNotificationReceived, object: nil)
}
else{
//create a new view controller and add it to the hierarchy
}
}
completionHandler(.newData)
}

现在任何对象都可以监听此通知并执行其需要的任何操作。您只需在需要时订阅和取消订阅即可。在您的情况下,明智的做法是在 viewWillAppear 和 viewDidDisappear 方法中执行此操作:

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.refresh), name: Notification.Name.pushNotificationReceived, object: nil)
}

override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: Notification.Name.pushNotificationReceived, object: nil)
}

func refresh() {
//do your stuff here
}

关于ios - 在特定的 viewController 中处理 PushNotifcations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39905465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com