gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:02:57 25 4
gpt4 key购买 nike

我在 Swift 1.2 中使用了这个

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

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

stringByAddingPercentEncodingWithAllowedCharacters

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

我想使用的示例网址如下

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

用于编码的 URL 字符集似乎包含修剪我的设置网址。即,

The path component of a URL is the component immediately following the host component (if present). It ends wherever the query or fragment component begins. For example, in the URL http://www.example.com/index.php?key1=value1, the path component is /index.php.

但是我不想修剪它的任何方面。当我使用我的字符串时,例如 myurlstring 它会失败。

但是当使用以下内容时,就没有问题了。它用一些魔法对字符串进行了编码,我可以获得我的 URL 数据。

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

就这样

Returns a representation of the String using a given encoding to determine the percent escapes necessary to convert the String into a legal URL string

谢谢

最佳答案

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

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

是字符集URLQueryAllowedCharacterSet

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())

Swift 3:

let urlwithPercentEscapes = myurlstring.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)

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

由于方法 stringByAddingPercentEncodingWithAllowedCharacters 可以返回 nil,因此请按照 Leo Dabus 的答案中的建议使用可选绑定(bind)。

关于string - 如何在 Swift 2.0 中使用 stringByAddingPercentEncodingWithAllowedCharacters() 作为 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39719451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com