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.