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

我想我的swift iOS应用程序调用自定义url的查询函数。 我有这样的urlmyApp://q=string 。 我想启动我的应用程序并调用string函数。 我已经注册了Xcode中的url,我的应用程序通过在Safari地址栏中inputmyApp://来启动。 这是我到目前为止在我的AppDelegate.swift:

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

我如何获得查询string所以我可以调用myfunction(string)

您的url

 myApp://q=string 

不符合RFC 1808“相对统一资源定位符” 。 URL的一般forms是

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

这在你的情况是

 myApp://?q=string 

问号开始URL的查询部分。 使用 URL,您可以使用NSURLComponents类来提取各个部分,如查询string及其项目:

 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 } } } } } 

NSURLComponents类在iOS 8.0及更高版本中可用。

注意:对于简单的URL,您可以使用简单的string方法直接提取查询参数的值:

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

但是,如果您稍后决定添加更多的查询参数,则使用NSURLComponents更不容易出错并且更加灵活。