swiftviewcontrollerappdelegateunusernotificationcenterusernotifications

Present a specific view controller from notification action


I'm working with local notifications and I'm trying to present a specific viewController but I have tried what I've found in this forum and I got an unusual behavior with the view shown in this picture here: And here's the source code of 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
            })
        }
    }
}

What is wrong with the code (especially the redirectToVC() method)? Any help will be appreciated.


Solution

  • I just found an answer to this. It's basically presenting a view controller from 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()
    }
    

    Thanks to Opening view controller from app delegate using swift