簡體   English   中英

根據推送通知從 Appdelegate 更改視圖

[英]Change View from Appdelegate depending on push notification

您好需要根據我的推送通知中顯示的標題從我的 Appdelegate 更改 ViewController。 正如您在下面的擴展中看到的那樣,我在前台模式下按下它后會收到我的推送通知並進行測試,如果它包含以下文本:“Dein Freund ist am Joggen”。 它包含應該切換視圖控制器的文本。 我已經嘗試了以下文章中的方法:

使用 swift 從應用委托打開視圖 controller

主要問題是我沒有 window 並聲明 window: UIwindow? 或類似的東西根本沒有幫助。 所以我的問題是如何強制在這里顯示 Viewcontroller

我已經初始化了我的 storyboard 並且應該顯示我的 requestPage。

let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let requestPage = storyboard.instantiateViewController(withIdentifier: "Requester") as! RequestViewController

這是擴展的完整代碼

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // Change this to your preferred presentation option
    completionHandler([[.alert, .sound]])
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    let application = UIApplication.shared
     
     if(application.applicationState == .active){
        
       print("user tapped the notification bar when the app is in foreground")
        if(userInfo.description.contains("Dein Freund ist am Joggen")) {
            let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let requestPage = storyboard.instantiateViewController(withIdentifier: "Requester") as! RequestViewController
            
        }
     }
     
     if(application.applicationState == .inactive)
     {
       print("user tapped the notification bar when the app is in background")
     }

    completionHandler()
  }
}

有任何想法嗎?

我修復了這似乎是一個常見問題,所以我很樂意分享我的解決方案。 僅當您的項目中有 Scenedelegate 時才有效!

guard var rootViewController = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window?.rootViewController else {
           return
       }
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "Requester") as! RequestViewController
rootViewController.present(controller, animated: true, completion: { () -> Void in

})

暫無
暫無

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

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