我在使用这个,在Swift 1.2
let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)@H_404_2@这现在给了我一个警告,要求我使用
stringByAddingPercentEncodingWithAllowedCharacters@H_404_2@我需要使用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@H_404_2@用于编码的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)@H_404_2@就这样
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)@H_404_2@是字符集URLQueryAllowedCharacterSet
let urlwithPercentEscapes = myurlstring.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())@H_404_2@Swift 3:
let urlwithPercentEscapes = myurlstring.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)@H_404_2@它对URL字符串中问号后的所有内容进行编码。
由于方法stringByAddingPercentEncodingWithAllowedCharacters可以返回nil,使用可选绑定如Leo Dabus的答案中建议的。