Search code examples
iosuiviewcontrollerswift4today-extension

Containing App crashes when opened from Today extension in swift 4


i have a swift app for which i have a today extension,it has a button which opens the containing app.

the button opens the app perfectly when the app is in the recent list but crashes when the app is moved from the recent list.

there's no crashlogs too

this is my code on app delegate :

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    var mainViewController : MainViewController!
    mainViewController = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers[1].childViewControllers[0] as! MainViewController

    if url.scheme == "open"
    {
        switch url.host
        {
        case "1"?:
            mainViewController.isTaxi = true
            break
        case "2"?:
           mainViewController.isPfp = true
            break
        case "3"?:
           mainViewController.isDarbi = true
            break
        default:
            break
        }
    }
    return true
}

this is how i open in main VC :

var isTaxi : Bool? {
    didSet{
        if UserDefaults.getUser() != nil {
            self.taxiRegViewController.show()
        } else {
            self.taxiNotRegViewController.show()
        }
    }
}

this is where i fire tap event in extension :

@IBAction func bookTaxiTapped(_ sender: UIButton) {
    if let url = URL(string: "open://\(sender.tag)")
    {
        self.extensionContext?.open(url, completionHandler: nil)
    }
}

Solution

  • I solved my problem,by modifying the app delegate's method like this :

    Actual Problem was : we had SWRevealViewController which has to be initiated before calling other view controller's

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        var mainViewController : MainViewController!
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    
        let viewController = storyBoard.instantiateViewController(withIdentifier: "swRevealController") as! SWRevealViewController
        mainViewController = storyBoard.instantiateViewController(withIdentifier: "mainView") as! MainViewController
        self.window?.rootViewController = viewController
        self.window?.makeKeyAndVisible()
    
        viewController.setFront(mainViewController, animated: true)
    
    
        if url.scheme == "open"
        {
            switch url.host
            {
            case "1"?:
                mainViewController.isTaxi = true
                break
            case "2"?:
               mainViewController.isPfp = true
                break
            case "3"?:
               mainViewController.isDarbi = true
                break
            default:
                break
            }
        }
        return true
    }