如何在Swift 2.0中使用stringByAddingPercentEncodingWithAllowedCharacters()作为URL
我正在使用这个,在Swift 1.2中
let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
这现在给我一个警告,要我使用
stringByAddingPercentEncodingWithAllowedCharacters
我需要使用一个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
编码的URL字符集似乎包含修剪我的URL。 即
URL的path组件是紧跟在主机组件之后的组件(如果存在)。 它在查询或片段组件开始的任何地方结束。 例如,在URL http://www.example.com/index.php?key1=value1中 ,path组件是/index.php。
不过,我不想削减它的任何方面。 当我使用我的string,例如myurlstring
它会失败。
但是,当使用以下,那么没有问题。 它用一些魔术编码string,我可以得到我的URL数据。
let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
就这样
使用给定的编码返回String的表示forms,以确定将String转换为合法URLstring所需的百分比转义
谢谢
对于给定的URLstring等同于
let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
是字符集URLQueryAllowedCharacterSet
let urlwithPercentEscapes = myurlstring.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())
Swift 3:
let urlwithPercentEscapes = myurlstring.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
它在URLstring中的问号之后编码所有内容。
由于stringByAddingPercentEncodingWithAllowedCharacters
方法可以返回nil,所以使用Leo Dabus答案中build议的可选绑定。
这将取决于你的url。 如果你的url是一个path,你可以使用字符集urlPathAllowed
let myFileString = "My File.txt" if let urlwithPercentEscapes = myFileString.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) { print(urlwithPercentEscapes) // "My%20File.txt" }
为URL编码创build一个字符集
urlFragmentAllowed
urlHostAllowed
urlPasswordAllowed
urlQueryAllowed
urlUserAllowed
你也可以创build你自己的url字符集:
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)
extension CharacterSet { static let urlAllowed = CharacterSet.urlFragmentAllowed .union(.urlHostAllowed) .union(.urlPasswordAllowed) .union(.urlQueryAllowed) .union(.urlUserAllowed) }
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" }
另一个select是使用URLComponents来正确地创build你的url
SWIFT 3.0
从grokswift
从string创buildURL是一个错误的雷区。 只是错过一个/或意外的URL编码? 在查询中,您的API调用将失败,您的应用程序将不会显示任何数据(甚至在您没有预料到可能的情况下会崩溃)。 从iOS 8开始,使用NSURLComponents
和NSURLQueryItems
更好地构buildURL。
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 }
以下是使用guard
语句访问url的代码。
guard let url = createURLWithComponents() else { print("invalid URL") return nil } print(url)
输出:
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
在我的情况下,最后一个组件是非拉丁字符,我在Swift 2.2中做了以下操作:
extension String { func encodeUTF8() -> String? { //If I can create an NSURL out of the string nothing is wrong with it if let _ = NSURL(string: self) { return self } //Get the last component from the string this will return subSequence let optionalLastComponent = self.characters.split { $0 == "/" }.last if let lastComponent = optionalLastComponent { //Get the string from the sub sequence by mapping the characters to [String] then reduce the array to String let lastComponentAsString = lastComponent.map { String($0) }.reduce("", combine: +) //Get the range of the last component if let rangeOfLastComponent = self.rangeOfString(lastComponentAsString) { //Get the string without its last component let stringWithoutLastComponent = self.substringToIndex(rangeOfLastComponent.startIndex) //Encode the last component if let lastComponentEncoded = lastComponentAsString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()) { //Finally append the original string (without its last component) to the encoded part (encoded last component) let encodedString = stringWithoutLastComponent + lastComponentEncoded //Return the string (original string/encoded string) return encodedString } } } return nil; } }
在Swift 3.1中,我正在使用如下所示的内容:
let query = "param1=value1¶m2=" + valueToEncode.addingPercentEncoding(withAllowedCharacters: .alphanumeric)
它比.urlQueryAllowed和其他的更安全,因为它将编码AZ,az和0-9以外的所有字符。 当您编码的值可能使用特殊字符(如?,&,=,+和空格)时,此function会更好。