如何将stringByAddingPercentEncodingWithAllowedCharacters()用于Swift 2.0中的URL
我在Swift 1.2中使用了这个如何将stringByAddingPercentEncodingWithAllowedCharacters()用于Swift 2.0中的URL,string,swift,swift2,nscharacterset,String,Swift,Swift2,Nscharacterset,我在Swift 1.2中使用了这个 let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) 这给了我一个警告,要求我使用 stringByAddingPercentEncodingWithAllowedCharacters 我需要使用NSCharacterSet作为参数,但是有太多的参数,我无法确定哪一个参数会给我与以前使用的方法相同的结果
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字符集似乎包含修剪集
网址。i、 e
URL的路径组件是紧跟在
主机组件(如果存在)。无论查询或片段在何处结束
组件开始。例如,在URL中
,路径组件为
/index.php
然而,我不想修剪它的任何方面。
当我使用我的字符串时,例如myurlstring
它会失败
但是当使用下面的方法时,就没有问题了。它用一些魔法对字符串进行编码,我可以得到我的URL数据
let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
因为它
使用给定的编码将字符串的表示形式返回给
确定将字符串转换为字符串所需的转义百分比
合法URL字符串
谢谢这将取决于您的url。如果url是路径,则可以使用字符集 允许使用URLfragments 允许使用URL主机 urlPasswordAllowed 乌尔克勒维德 urlUserAllowed 您还可以创建自己的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)
另一个选项是对于给定的URL字符串
let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
是字符集URLQueryAllowedCharacterSet
let urlwithPercentEscapes = myurlstring.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())
Swift 3:
let urlwithPercentEscapes = myurlstring.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
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
它对URL字符串中问号后面的所有内容进行编码
由于方法
stringByAddingPercentEncodingWithAllowedCharacters
可以返回nil,因此请按照Leo Dabus的回答中的建议使用可选绑定。在最后一个组件是非拉丁字符的情况下,我在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.0(来自) 从字符串创建URL是bug的雷区。只是错过了一个或偶然的URL编码?在查询中,您的API调用将失败,并且您的应用程序将不会显示任何数据(如果您没有预料到这种可能性,甚至会崩溃)自从iOS 8以来,有一种更好的方法可以使用
NSURLComponents
和NSURLQueryItems
构建URL
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)
输出:
let urlwithPercentEscapes = myurlstring.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
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 3.1中,我使用了如下内容:
let query = "param1=value1¶m2=" + valueToEncode.addingPercentEncoding(withAllowedCharacters: .alphanumeric)
它比.urlQueryAllowed和其他字符更安全,因为它将对除A-Z、A-Z和0-9之外的所有字符进行编码。当您正在编码的值可能使用特殊字符,如?、&、=、+和空格时,这种方法效果更好。Swift 4.0
let encodedData = myUrlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)
请参阅问题以了解更多信息更重要的是,您需要将适当的字符集应用于URL的每个部分,因为不同的部分具有不同的功能,所以没有单一的解决方案…不起作用,例如,您建议的集返回此内容,http%3A//www.mapquestapi.com/geocoding/v1/batch%3Fkey=但使用的旧方法,给我的@Wain非常真实,这也是警告所说的。只在有空格的部分使用此答案中的集合似乎有效。@DogCoffee您可以创建一个自定义集合,这很有意义,谢谢-如果您有时间,您能帮我吗
let encodedData = myUrlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)