How to use UIApplication and openURL and call a swift function on “string” from foo://q=string?

末鹿安然 提交于 2019-12-11 04:45:54

问题


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)?


回答1:


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.



来源:https://stackoverflow.com/questions/27647577/how-to-use-uiapplication-and-openurl-and-call-a-swift-function-on-string-from

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!