当用户点击带有 iOS 13 Swift 5 的推送通知时,在特定视图中打开应用程序

Open app in specific view when user taps on push notification with iOS 13 Swift 5

我的应用允许向用户远程推送通知。当用户点击推送通知时,如何让它在特定的视图控制器中打开?我希望应用程序根据收到的推送通知打开并导航到特定的视图控制器。

您必须使用“ func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool{ :

中的启动选项检查您的应用何时处于关闭状态
 if let option = launchOptions {
    let info = option[UIApplication.LaunchOptionsKey.remoteNotification]
         if (info != nil) {
            self.goAnotherVC()
     }
}

并在你的着陆视图中加载 VC 设置观察者

 NotificationCenter.default.addObserver(self, selector: #selector(self.goToVc(notification:)), name:NSNotification.Name(rawValue:identifier), object: nil)

选择器方法:

 @objc func goToVc(notification:Notification) {
     let storyboard = UIStoryboard(name: "Main", bundle: nil)
     let vc = storyboard.instantiateViewController(withIdentifier:"landingVC") as! landingVC
     self.navigationController?.pushViewController(vc, animated: true)  
}

在应用委托中:

func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
     NotificationCenter.default.post(name:NSNotification.Name(identifier), object: userInfo)
  }

您可以在收到并且用户点击通知后触发通知

与通知一起,您可以传递值,该值稍后将用于标识您需要导航到哪个视图控制器。

创建一个 class,它将负责所有推送通知导航处理。您可以将其命名为 PushNotificationHandler。让 PushNotificationHandler 处理程序处理导航到视图控制器的所有逻辑。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
} 
  • 使用上面的委托方法
  • 从深层获取值link
  • 触发值为
  • 的通知
  • PushNotificationHandler中处理通知class

此答案适用于 iOS 13+

在 AppDelegae 中:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
   
        NotificationCenter.default.post(name: NSNotification.Name(identifier), object: nil)
        completionHandler()
}

viewDidLoad的登陆ViewController:

override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.showChatController(notification:)), name:NSNotification.Name(rawValue: "noti"), object: nil)    
}

在您的登陆 viewController 添加以下选择器方法:

@objc
func showChatController(notification: Notification) {
print("DEBUG: show chat controller here..")
        
}