如何在Swift 2.0中使用stringByAddingPercentEncodingWithAllowedCharacters()作为URL

Dog*_*fee 63 string nscharacterset swift swift2

我在Swift 1.2中使用它

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
Run Code Online (Sandbox Code Playgroud)

现在这给了我一个警告,要求我使用

stringByAddingPercentEncodingWithAllowedCharacters
Run Code Online (Sandbox Code Playgroud)

我需要使用NSCharacterSet作为参数,但是有很多,我无法确定哪个会给我与之前使用的方法相同的结果.

我想要使​​用的示例URL将是这样的

http://www.mapquestapi.com/geocoding/v1/batch?key=YOUR_KEY_HERE&callback=renderBatch&location=Pottsville,PA&location=Red Lion&location=19036&location=1090 N Charlotte St, Lancaster, PA
Run Code Online (Sandbox Code Playgroud)

用于编码的URL字符集似乎包含修剪我的URL的设置.即

URL的路径组件是紧跟主机组件(如果存在)的组件.它在查询或片段组件开始的任何地方结束.例如,在URL http://www.example.com/index.php?key1=value1中,路径组件是/index.php.

但是我不想削减它的任何方面.当我使用我的String时,例如myurlstring它会失败.

但是当使用以下内容时,则没有问题.它用一些魔法编码了字符串,我可以得到我的URL数据.

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
Run Code Online (Sandbox Code Playgroud)

就这样

使用给定的编码返回String的表示形式,以确定将String转换为合法URL字符串所需的转义百分比

谢谢

vad*_*ian 151

对于给定的URL字符串,相当于

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
Run Code Online (Sandbox Code Playgroud)

是字符集 URLQueryAllowedCharacterSet

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())
Run Code Online (Sandbox Code Playgroud)

斯威夫特3:

let urlwithPercentEscapes = myurlstring.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
Run Code Online (Sandbox Code Playgroud)

它对URL字符串中的问号后面的所有内容进行编码.

由于该方法stringByAddingPercentEncodingWithAllowedCharacters可以返回nil,因此请使用Leo Dabus答案中建议的可选绑定.


Leo*_*bus 17

这取决于你的网址.如果您的网址是路径,则可以使用字符集 urlPathAllowed

let myFileString = "My File.txt"
if let urlwithPercentEscapes = myFileString.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) {
    print(urlwithPercentEscapes)  // "My%20File.txt"
}
Run Code Online (Sandbox Code Playgroud)

为URL编码创建字符集

urlFragmentAllowed

urlHostAllowed

urlPasswordAllowed

urlQueryAllowed

urlUserAllowed

您还可以创建自己的网址字符集:

let myUrlString = "http://www.mapquestapi.com/geocoding/v1/batch?key=YOUR_KEY_HERE&callback=renderBatch&location=Pottsville,PA&location=Red Lion&location=19036&location=1090 N Charlotte St, Lancaster, PA"

let urlSet = CharacterSet.urlFragmentAllowed
                .union(.urlHostAllowed)
                .union(.urlPasswordAllowed)
                .union(.urlQueryAllowed)
                .union(.urlUserAllowed)
Run Code Online (Sandbox Code Playgroud)
extension CharacterSet {
    static let urlAllowed = CharacterSet.urlFragmentAllowed
                                        .union(.urlHostAllowed)
                                        .union(.urlPasswordAllowed)
                                        .union(.urlQueryAllowed)
                                        .union(.urlUserAllowed)
}
Run Code Online (Sandbox Code Playgroud)
if let urlwithPercentEscapes = myUrlString.addingPercentEncoding(withAllowedCharacters: .urlAllowed) {
    print(urlwithPercentEscapes)  // "http://www.mapquestapi.com/geocoding/v1/batch?key=YOUR_KEY_HERE&callback=renderBatch&location=Pottsville,PA&location=Red%20Lion&location=19036&location=1090%20N%20Charlotte%20St,%20Lancaster,%20PA"
}
Run Code Online (Sandbox Code Playgroud)

另一个选择是使用URLComponents来正确创建您的网址

  • 更重要的是,您需要将适当的字符集应用于URL的每个部分,没有单一的解决方案,因为不同的部分具有不同的功能...... (3认同)

Ash*_*k R 7

Swift 3.0(来自grokswift)

从字符串创建URL是bug的一个雷区.只是错过一个/或不小心的URL编码?在查询中,您的API调用将失败,您的应用程序将不会显示任何数据(如果您没有预料到这种可能性,甚至会崩溃).从iOS 8开始,有一种更好的方法来使用NSURLComponents和构建URL NSURLQueryItems.

func createURLWithComponents() -> URL? {
        var urlComponents = URLComponents()
        urlComponents.scheme = "http"
        urlComponents.host = "www.mapquestapi.com"
        urlComponents.path = "/geocoding/v1/batch"

        let key = URLQueryItem(name: "key", value: "YOUR_KEY_HERE")
        let callback = URLQueryItem(name: "callback", value: "renderBatch")
        let locationA = URLQueryItem(name: "location", value: "Pottsville,PA")
        let locationB = URLQueryItem(name: "location", value: "Red Lion")
        let locationC = URLQueryItem(name: "location", value: "19036")
        let locationD = URLQueryItem(name: "location", value: "1090 N Charlotte St, Lancaster, PA")

        urlComponents.queryItems = [key, callback, locationA, locationB, locationC, locationD]

        return urlComponents.url
}
Run Code Online (Sandbox Code Playgroud)

下面是使用guardstatement 访问url的代码.

guard let url = createURLWithComponents() else {
            print("invalid URL")
            return nil
      }
      print(url)
Run Code Online (Sandbox Code Playgroud)

输出:

http://www.mapquestapi.com/geocoding/v1/batch?key=YOUR_KEY_HERE&callback=renderBatch&location=Pottsville,PA&location=Red%20Lion&location=19036&location=1090%20N%20Charlotte%20St,%20Lancaster,%20PA
Run Code Online (Sandbox Code Playgroud)