1

我正在使用本地通知,並試圖呈現特定的viewController,但我嘗試了在此論壇中找到的內容,並且看到顯示的視圖出現異常行爲在 this picture here: 而這裏的AppDelegate.swift的源代碼:從通知動作中呈現特定的視圖控制器

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

    print("didReceive Method called") 

    if response.actionIdentifier == "actionOne" { 
     DispatchQueue.main.async(execute: { 
      self.notificationAction1() 
     }) 
    } else if response.actionIdentifier == "actionTwo" { 
     DispatchQueue.main.async(execute: { 
      self.notificationAction2() 
     }) 

    } else if response.actionIdentifier == "actionThree" { 

    } 
    completionHandler() 
} 

func notificationAction1() { 
    redirectToVC() 
} 

func redirectToVC() { 
    let toVC = VersesViewController() 
    if self.window != nil && self.window?.rootViewController != nil { 
     let rootVC = self.window?.rootViewController! 
     if rootVC is UINavigationController { 
      (rootVC as! UINavigationController).pushViewController(toVC, animated: true) 
     } else { 
      rootVC?.present(toVC, animated: true, completion: { 
       //Do something 
      }) 
     } 
    } 
} 

什麼是錯的代碼(尤其是redirectToVC()方法)? 任何幫助將不勝感激。

+0

它目前的作品? – Mannopson

+0

看看源代碼上面的圖片,視圖控制器是空白的,它不應該是。 –

回答

1

我剛剛找到了答案。它基本上是從AppDelegate展示一個視圖控制器。

func redirectToVC() { 
    let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
    let initialViewController: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "versesVC") as UIViewController 
    self.window = UIWindow(frame: UIScreen.main.bounds) 
    self.window?.rootViewController = initialViewController 
    self.window?.makeKeyAndVisible() 
} 

由於Opening view controller from app delegate using swift

+0

它完美的作品? – Mannopson

+0

我也設置rootViewController像這樣,但問題是我的默認rootView是一個發射器動畫視圖。它將顯示一個動畫,然後它將重定向到另一個視圖並將其設置爲rootView。但是,當我重置我的rootView到'didReceive響應:'它顯示特定的ViewController一眼,然後回到舊的rootViewController。我怎樣才能防止它回到舊的rootViewController? –

0

只要你有展示當前屏幕上的特定視圖控制器,它不是,如果你視圖 - 控制器通過導航推或可能呈現沒關係,在這兩種情況下,你可以在下面使用代碼來解決你的問題。

    var appdelgateObj = UIApplication.shared.delegate as! AppDelegate 
        if let destinationVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: 「ToPresentVC」) as? ToPresentVC { 
         if let window = appdelgateObj.window , let rootViewController = window.rootViewController { 
          var currentController = rootViewController 
          while let presentedController = currentController.presentedViewController { 
           currentController = presentedController 
          } 
          currentController.present(destinationVC, animated: true, completion: nil) 
         } 
        } 
相關問題