andy andy - 1 year ago 104
iOS Question

How to connect Universal Links to UIViewController?

*Disclaimer: I've only been coding in iOS/XCode/Swift for a couple of weeks

I have Universal Links working in that clicking a link outside my app opens up the app and I catching the Url in the AppDelegate class.

So that's all good.

My question is... how do I then redirect to the correct UIViewController AND pass the controller some info from my URL? All Universal Link tutorials stop before they get to that part.

In particular I'm confused about the lifecycles of AppDelegate and how it relates to UIViewController.

What I've tried

I have tried handling the url event in AppDelegate, and setting a public property, and then in my ViewController getting access to the AppDelegate. HOWEVER, after the Universal Link is clicked, both
don't get called again :-/

What's the best way to redirect to a ViewController from AppDelegate? My goal is simply to load the root view controller BUT I need to pass in some data from the URL. How?

Answer Source
  1. First, Read your URL.
  2. Get your parameters from URL
  3. Initiate your target controller
  4. Set your parameter to that controller
  5. Present controller on root view controller

        let urlString = url.absoluteString
        let queryArray = urlString.componentsSeparatedByString("/")
        if queryArray[2].lowercaseString == "yourQuery" {
            let queryId = Int(queryArray[3])
            if self.window?.rootViewController?.presentedViewController != nil {
                self.window?.rootViewController?.dismissViewControllerAnimated(false, completion: nil)
            let queryVC = self.window?.rootViewController?.storyboard?.instantiateViewControllerWithIdentifier(QUERY_SCENE) as? QueryViewController
            queryVC?.urlQueryId = queryId!
            self.window?.rootViewController?.presentViewController(queryVC!, animated: true, completion: nil)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download