如何使用UIApplication和openURL并在“string”上调用swift函数来自foo:// q = string? [英] How to use UIApplication and openURL and call a swift function on "string" from foo://q=string?

查看:455
本文介绍了如何使用UIApplication和openURL并在“string”上调用swift函数来自foo:// q = string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的swift iOS应用程序能够在自定义网址的查询中调用函数。我有一个这样的网址 myApp:// q = string 。我想启动我的应用并在 string 上调用一个函数。我已经在Xcode中注册了网址,我的应用程序通过在Safari地址栏中输入 myApp:// 来启动。这是我到目前为止在AppDelegate.swift中所拥有的:

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
}

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

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

推荐答案

您的网址

myApp://q=string

不符合 RFC 1808相对统一资源定位器。 URL的一般形式是

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>

在您的情况下将是

myApp://?q=string

其中的问号启动URL的查询部分。使用 URL,
,您可以使用 NSURLComponents 类来提取各种部分,例如
作为查询字符串及其items:

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

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

The NSURLComponents class is available on iOS 8.0 and later.

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

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

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

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

这篇关于如何使用UIApplication和openURL并在“string”上调用swift函数来自foo:// q = string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆