ios - 推送通知 - 使用 SceneDelegate 在通知点击时推送 ViewController

标签 ios swift

在 iOS 13 之前,导航 Controller 和 Root View 是在 AppDelegate 中定义的。然而,在 iOS 13 中,Apple 引入了 SceneDelegate,它接管了这些 View 函数的处理。然而,AppDelegate 仍然处理诸如本地通知处理之类的事情。 See this answer for some code that outlines these changes for root views.

如果我希望在用户点击本地通知时推送 View ,我会在 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 开始,我的项目的根导航 Controller 现在可以在 SceneDelegate 中定义,因此我似乎无法弄清楚如何在由 SceneDelegate 而不是 AppDelegate 管理的导航 Controller 中推送 View 。

最佳答案

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()
    }
  }
}

关于ios - 推送通知 - 使用 SceneDelegate 在通知点击时推送 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59675593/

相关文章:

ios - Swift:使用 Localizable.stringsdict 的本地化字符串中的千位分隔符

ios - 类型 NSAttributedString 在 tableView 中没有下标成员

iphone - 导航栏位于隐藏状态栏下方

ios - 构建失败 'React/RCTBridgeModule.h' 找不到文件

ios - 如何在不与服务器通信的情况下阻止 WKWebView 中的 304 请求加载缓存图像?

iOS计算重力

swift - 用户录制音频时创建语音频率图?

iphone - 模态视图 Controller 因内存警告而被解雇?

快速信号量命令行工具项目等待组完成

ios - 手动设置时节标题高度不同