簡體   English   中英

推送通知 - 在通知點擊時使用 SceneDelegate 推送一個 ViewController

[英]Push Notifications - Push a ViewController upon Notification Tap with SceneDelegate

在 iOS 13 之前,導航控制器和根視圖是在 AppDelegate 中定義的。 然而,在 iOS 13 中,Apple 引入了 SceneDelegate,它接管了這些視圖函數的處理。 但是,AppDelegate 仍然處理諸如本地通知處理之類的事情。 有關概述根視圖的這些更改的一些代碼,請參閱此答案。

如果我想在用戶點擊本地通知時推送視圖,我會在 AppDelegate 中執行以下操作:

extension AppDelegate: UNUserNotificationCenterDelegate {

    var navigationController: UINavigationController?

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        if response.actionIdentifier == UNNotificationDefaultActionIdentifier { //User taps notification
             let vc = MyViewController()
             self.navigationController?.pushViewController(vc, animated: true)
        }
    }
}

但是,由於我的項目的根導航控制器現在可以在 iOS 13 的 SceneDelegate 中定義,我似乎無法弄清楚如何在由 SceneDelegate 而不是 AppDelegate 管理的導航控制器中推送視圖。

SceneDelegate可以這樣處理通知響應:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
  func scene(
    _ scene: UIScene,
    willConnectTo session: UISceneSession,
    options connectionOptions: UIScene.ConnectionOptions
  ) {
    if let windowScene = scene as? UIWindowScene {
      let window = UIWindow(windowScene: windowScene)
      // rootViewController set up code
      // say,
      // let mainController = ViewController()
      // let navigationController = UINavigationController(rootViewController: mainController)
      // window.rootViewController = navigationController

      // This is UNNotificationResponse
      if let notificationResponse = connectionOptions.notificationResponse {
        window.makeKeyAndVisible()
        // do the pushing on your navigation controller
        // navigationController.push()
        return
      }

      window.makeKeyAndVisible()
    }
  }
}

如果您的應用程序支持多窗口或單一窗口,你可以使用targetScene物業UNNotificationResponse決定通知會推出哪些場景(窗口)。

例子:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    guard let windowSceneDelegate = response.targetScene?.delegate as? UIWindowSceneDelegate,
          let window = windowSceneDelegate.window,
          let rootViewController = window.rootViewController as? UINavigationController else {
        completionHandler()
        return
    }
    let notificationViewController = UIViewController()
    rootViewController.pushViewController(notificationViewController, animated: true)
    completionHandler()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM