加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在Swift 2.0中使用stringByAddingPercentEncodingWithAllowe

发布时间:2020-12-14 06:04:08 所属栏目:百科 来源:网络整理
导读:我在使用这个,在Swift 1.2 let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) 这现在给了我一个警告,要求我使用 stringByAddingPercentEncodingWithAllowedCharacters 我需要使用NSCharacterSet
我在使用这个,在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
07000,the path component is
/index.php.

但我不想修剪它的任何方面。
当我使用我的String,例如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的答案中建议的。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读