如果应用通过推送通知打开,则设置Root View Controller会有所不同

时间:2017-10-18 14:28:26

标签: ios swift push-notification

我的应用程序默认启动,但在某些情况下,我希望应用程序通过推送通知打开,该推送通知会提供标识要加载的页面的有效负载。

我遇到的问题是有效负载逻辑在didRecieve响应中处理推送通知,我还处理在didFinishLaunchingWithOptions中启动的应用程序。

如何阻止这两个冲突,因为它似乎会使应用程序崩溃。

基本上我想根据通知中的有效负载更改启动时的根目录。

目前我有:

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // map
    let conferenceID = userInfo["cid"] as! String
    self.pushNotifiedEventID = conferenceID
    self.defaultEvent = conferenceID
    if let p = userInfo["p"] as? [String : String] {
        let pageID = p["id"]!
        let title = p["title"]!
        let type = p["type"]!
    }
    completionHandler()
    let hostViewController = HostViewController()
    self.window?.rootViewController = hostViewController
}

还有:

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if #available(iOS 10.0, *) {
        center.delegate = self
        center.requestAuthorization(options: [.badge, .alert , .sound]) { (granted, error) in
            if granted {
                DispatchQueue.main.async(execute: {
                    UIApplication.shared.registerForRemoteNotifications()
                })
            }
        }
    } else {
        let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
        let setting = UIUserNotificationSettings(types: type, categories: nil)
        UIApplication.shared.registerUserNotificationSettings(setting)
        UIApplication.shared.registerForRemoteNotifications()
    }
    // root VC init + push
    window = UIWindow()
    let loginViewController = LoginViewController.init(loginView: LoginView(frame: UIScreen.main.bounds))
    self.navigationController = UINavigationController(rootViewController: loginViewController)
    window?.rootViewController = navigationController
    window?.makeKeyAndVisible()
    return true
}

1 个答案:

答案 0 :(得分:0)

在AppDelegate类中,创建一个方法:

func configureRootView(isComingFromNotification: Bool) {
  if isComingFromNotification {
    self.window?.rootViewController = HostViewController()
  }
  else {
    let loginViewController = LoginViewController.init(loginView: LoginView(frame: UIScreen.main.bounds))
    self.navigationController = UINavigationController(rootViewController: loginViewController)
    window?.rootViewController = navigationController
  }
}

您可以使用func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool方法调用此方法。