简体   繁体   English

如何使用UIApplication和openURL并从foo:// q = string的“ string”上调用swift函数?

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

I would like my swift iOS app to call a function on a custom url's query. 我希望我的iOS应用程序能够在自定义网址的查询中调用函数。 I have a url like this myApp://q=string . 我有一个类似myApp://q=string的网址。 I would like to launch my app and call a function on string . 我想启动我的应用程序并在string上调用一个函数。 I have already registered the url in Xcode and my app launches by typing myApp:// in the Safari address bar. 我已经在Xcode中注册了该网址,并且通过在Safari地址栏中键入myApp://来启动我的应用程序。 This is what I have so far in my AppDelegate.swift: 这是我到目前为止在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) ? 如何获取查询string以便可以调用myfunction(string)

Your URL 您的网址

myApp://q=string

does not conform to the RFC 1808 "Relative Uniform Resource Locators" . 不符合RFC 1808“相对统一资源定位符” The general form of an URL is URL的一般形式是

<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. 问号开始URL的查询部分。 With that URL, you can use the NSURLComponents class to extract the various parts such as the query string and its items: 使用 URL,您可以使用NSURLComponents类提取各个部分,例如查询字符串及其项:

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. NSURLComponents类在iOS 8.0和更高版本上可用。

Note: In the case of your simple URL you could extract the value of the query parameter directly using simple string methods: 注意:对于简单的URL,您可以使用简单的字符串方法直接提取查询参数的值:

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. 但是,如果您决定以后再添加更多查询参数,则使用NSURLComponents不太容易出错,并且更灵活。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM