Adam
Adam

Reputation: 2398

How to send data from AppDelegate to my subclass of ViewController in swift 4

I am using Swift 4.1 and I am wondering how to pass the url data that is given here:

func application(_ app: UIApplication, open url: URL,
                    options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
}

into my subclass of UIViewController I called HotSpotRISViewController. Here is what I attempted:

func application(_ app: UIApplication, open url: URL,
                    options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
    self.window = UIWindow(frame: UIScreen.main.bounds)
    let vc = HotSpotRISViewController()
    vc.setURL(theURL: url)
    let navigationController = UINavigationController(rootViewController: vc)
    self.window!.rootViewController = navigationController

}

My HotSpotRISViewController contains this function:

func setURL(theURL: URL) {
    self.url = theURL
    print(self.url ?? "nil")
}

Inside my HotSpotRISViewController I have a property of type URL ready to be set. The above code correctly passes the info, because my print statement prints out the URL, but I get a black screen instead of my app. What am I missing? And then on the other hand, the following makes the app start up correctly but I have no idea how to pass the url data using this method:

func application(_ app: UIApplication, open url: URL,
                    options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
    let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let initialViewController = mainStoryboard.instantiateInitialViewController()
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()
}

I'm wondering how I can get both my app started up correctly without a black screen and pass the url data. Thank you.

Upvotes: 0

Views: 774

Answers (1)

PhillipJacobs
PhillipJacobs

Reputation: 2490

You can add a global variable in your appDelegate file and fetch it with your setURL function :

In your AppDelegate.swift

    var myurl: URL!
    ....

    func application(_ app: UIApplication, open url: URL,
                options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
        self.myurl = url
        let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = mainStoryboard.instantiateInitialViewController()
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()
    }
    ...

In your HotSpotRISViewController.swift

func setURL(theURL: URL) {
    DispatchQueue.main.async {
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
            self.url = appDelegate.myurl
        }
    }

Upvotes: 3

Related Questions