1

I would like my swift iOS app to call a function on a custom url's query. I have a url like this myApp://q=string. I would like to launch my app and call a function on string. I have already registered the url in Xcode and my app launches by typing myApp:// in the Safari address bar. This is what I have so far in my AppDelegate.swift:

func application(application: UIApplication!, openURL url: NSURL!, sourceApplication: String!, annotation: AnyObject!) -> Bool {


    return true
}

How do I get the query string so I can call myfunction(string)?

webmagnets
  • 2,266
  • 3
  • 33
  • 60

1 Answers1

4

Your URL

myApp://q=string

does not conform to the RFC 1808 "Relative Uniform Resource Locators". The general form of an URL is

<scheme>://<net_loc>/<path>;<params>?<query>#<fragment>

which in your case would be

myApp://?q=string

where the question mark starts the query part of the URL. With that URL, you can use the NSURLComponents class to extract the various parts such as the query string and its items:

if let urlComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) {
    if let queryItems = urlComponents.queryItems as? [NSURLQueryItem]{
        for queryItem in queryItems {
            if queryItem.name == "q" {
                if let value = queryItem.value {
                    myfunction(value)
                    break
                }
            }
        }
    }
}

The NSURLComponents class is available on iOS 8.0 and later.

Note: In the case of your simple URL you could extract the value of the query parameter directly using simple string methods:

if let string = url.absoluteString {
    if let range = string.rangeOfString("q=") {
        let value = string[range.endIndex ..< string.endIndex]
        myFunction(value)
    }
}

But using NSURLComponents is less error-prone and more flexible if you decide to add more query parameters later.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382