如果我对这样的字符串进行编码:
var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
它不会转义斜杠 /
。
我搜索并找到了这个目标 C 代码:
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8 );
有没有更简单的方法来编码 URL,如果没有,我该如何在 Swift 中编写它?
斯威夫特 3
在 Swift 3 中有 addingPercentEncoding
let originalString = "test/test"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(escapedString!)
输出:
测试%2F测试
斯威夫特 1
在 iOS 7 及更高版本中有 stringByAddingPercentEncodingWithAllowedCharacters
var originalString = "test/test"
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
println("escapedString: \(escapedString)")
输出:
测试%2F测试
以下是有用的(反转的)字符集:
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?@[\]^`
如果您想转义一组不同的字符,请创建一组:添加“=”字符的示例:
var originalString = "test/test=42"
var customAllowedSet = NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}").invertedSet
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
println("escapedString: \(escapedString)")
输出:
测试%2F测试%3D42
验证不在集合中的 ascii 字符的示例:
func printCharactersInSet(set: NSCharacterSet) {
var characters = ""
let iSet = set.invertedSet
for i: UInt32 in 32..<127 {
let c = Character(UnicodeScalar(i))
if iSet.longCharacterIsMember(i) {
characters = characters + String(c)
}
}
print("characters not in set: \'\(characters)\'")
}
您可以使用 URLComponents 来避免手动对查询字符串进行百分比编码:
let scheme = "https"
let host = "www.google.com"
let path = "/search"
let queryItem = URLQueryItem(name: "q", value: "Formula One")
var urlComponents = URLComponents()
urlComponents.scheme = scheme
urlComponents.host = host
urlComponents.path = path
urlComponents.queryItems = [queryItem]
if let url = urlComponents.url {
print(url) // "https://www.google.com/search?q=Formula%20One"
}
extension URLComponents {
init(scheme: String = "https",
host: String = "www.google.com",
path: String = "/search",
queryItems: [URLQueryItem]) {
self.init()
self.scheme = scheme
self.host = host
self.path = path
self.queryItems = queryItems
}
}
let query = "Formula One"
if let url = URLComponents(queryItems: [URLQueryItem(name: "q", value: query)]).url {
print(url) // https://www.google.com/search?q=Formula%20One
}
URLQueryItem
并不总是正确编码。例如,Formula+One
将被编码为 Formula+One
,而 Formula+One
将被解码为 Formula One
。因此,请谨慎使用加号。
URLComponents
,因为 URL 编码输出中的加号表示一个空格。
斯威夫特 4 & 5
要对 URL 中的参数进行编码,我发现使用 .alphanumerics
字符集是最简单的选项:
let urlEncoded = value.addingPercentEncoding(withAllowedCharacters: .alphanumerics)
let url = "http://www.example.com/?name=\(urlEncoded!)"
使用任何标准的 URL 编码字符集(如 URLQueryAllowedCharacterSet
或 URLHostAllowedCharacterSet
)都不起作用,因为它们不排除 =
或 &
字符。
注意,使用 .alphanumerics
会编码一些不需要编码的字符(如 -
、.
、_
或 ~
- 参见 2.3 . RFC 3986 中的未保留字符)。我发现使用 .alphanumerics
比构建自定义字符集更简单,并且不介意要编码一些额外的字符。如果这让您感到困扰,请按照 How to percent encode a URL String 中的说明构建自定义字符集,例如:
// Store allowed character set for reuse (computed lazily).
private let urlAllowed: CharacterSet =
.alphanumerics.union(.init(charactersIn: "-._~")) // as per RFC 3986
extension String {
var urlEncoded: String? {
return addingPercentEncoding(withAllowedCharacters: urlAllowed)
}
}
let url = "http://www.example.com/?name=\(value.urlEncoded!)"
警告: urlEncoded
参数被强制解包。对于无效的 unicode 字符串,它可能会崩溃。请参阅Why is the return value of String.addingPercentEncoding() optional?。您可以使用 urlEncoded ?? ""
或 if let urlEncoded = urlEncoded { ... }
,而不是强制展开 urlEncoded!
。
斯威夫特 5:
extension String {
var urlEncoded: String? {
let allowedCharacterSet = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "~-_."))
return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)
}
}
print("\u{48}ello\u{9}world\u{7}\u{0}".urlEncoded!) // prints Hello%09world%07%00
print("The string ü@foo-bar".urlEncoded!) // prints The%20string%20%C3%BC%40foo-bar
let originalString = "\u{48}ello\u{9}world\u{7}\u{0}"
变为 "Hello\tworld\u{07}\0"
。例如,控制字符或制表符不会被转义。
斯威夫特 3:
let originalString = "http://www.ihtc.cc?name=htc&title=iOS开发工程师"
1.编码查询:
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
结果:
"http://www.ihtc.cc?name=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88"
2.编码网址:
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
结果:
"http:%2F%2Fwww.ihtc.cc%3Fname=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88"
urlHostAllowed
对查询参数进行编码不正确,因为它不会对 ?
、=
和 +
进行编码。在对查询参数进行编码时,您必须分别正确地对参数名称和值进行编码。这在一般情况下不起作用。
urlHostAllowed
的任何解决方案/替代方案了吗
URLComponents
。
+
字符。所以唯一的选择是手动完成:CharacterSet.urlQueryAllowed.subtracting(CharacterSet(charactersIn: "+"))
Swift 4 & 5(感谢@sumizome 的建议。感谢@FD_ 和@derickito 的测试)
var allowedQueryParamAndKey = NSCharacterSet.urlQueryAllowed
allowedQueryParamAndKey.remove(charactersIn: ";/?:@&=+$, ")
paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey)
斯威夫特 3
let allowedQueryParamAndKey = NSCharacterSet.urlQueryAllowed.remove(charactersIn: ";/?:@&=+$, ")
paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey)
Swift 2.2(借用 Zaph's 并更正 url 查询键和参数值)
var allowedQueryParamAndKey = NSCharacterSet(charactersInString: ";/?:@&=+$, ").invertedSet
paramOrKey.stringByAddingPercentEncodingWithAllowedCharacters(allowedQueryParamAndKey)
例子:
let paramOrKey = "https://some.website.com/path/to/page.srf?a=1&b=2#top"
paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey)
// produces:
"https%3A%2F%2Fsome.website.com%2Fpath%2Fto%2Fpage.srf%3Fa%3D1%26b%3D2%23top"
这是 Bryan Chen 答案的简短版本。我猜想 urlQueryAllowed
允许控制字符通过,除非它们构成查询字符串中键或值的一部分,此时它们需要转义。
var
),然后在第二步中调用 .remove
。
斯威夫特 4:
这取决于您的服务器遵循的编码规则。
Apple 提供了此类方法,但它没有报告它遵循的那种 RCF 协议。
var escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
按照这个有用的 tool,您应该保证这些字符的编码用于您的参数:
$(美元符号)变为 %24
&(与号)变为 %26
+(加号)变为 %2B
,(逗号)变为 %2C
:(冒号)变为 %3A
; (分号)变为 %3B
=(等于)变为 %3D
? (问号)变为 %3F
@(商业 A / At)变为 %40
换句话说,说到 URL 编码,您应该遵循 RFC 1738 protocol。
例如,Swift 没有涵盖 + char 的编码,但它适用于这三个 @ : ?字符。
因此,要正确编码每个参数,.urlHostAllowed
选项是不够的,您还应该添加特殊字符,例如:
encodedParameter = parameter.replacingOccurrences(of: "+", with: "%2B")
希望这有助于疯狂搜索这些信息的人。
一切都一样
var str = CFURLCreateStringByAddingPercentEscapes(
nil,
"test/test",
nil,
"!*'();:@&=+$,/?%#[]",
CFStringBuiltInEncodings.UTF8.rawValue
)
// test%2Ftest
.bridgeToOvjectiveC()
第二个参数,也没有得到“无法转换表达式的类型 'CFString!'输入'CFString!'”?
斯威夫特 4.2
一种快速的单线解决方案。将 originalString
替换为您要编码的字符串。
var encodedString = originalString.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]{} ").inverted)
let originalString = "\u{48}ello\u{9}world\u{7}\u{0}"
被编码为 "Hello\tworld\u{07}\0"
。例如,控制字符或制表符不会被转义。
这在 Swift 5 中对我有用。用例是从剪贴板或类似的 URL 获取可能已经有转义字符但也包含可能导致 URLComponents
或 URL(string:)
失败的 Unicode 字符。
首先,创建一个包含所有 URL 合法字符的字符集:
extension CharacterSet {
/// Characters valid in at least one part of a URL.
///
/// These characters are not allowed in ALL parts of a URL; each part has different requirements. This set is useful for checking for Unicode characters that need to be percent encoded before performing a validity check on individual URL components.
static var urlAllowedCharacters: CharacterSet {
// Start by including hash, which isn't in any set
var characters = CharacterSet(charactersIn: "#")
// All URL-legal characters
characters.formUnion(.urlUserAllowed)
characters.formUnion(.urlPasswordAllowed)
characters.formUnion(.urlHostAllowed)
characters.formUnion(.urlPathAllowed)
characters.formUnion(.urlQueryAllowed)
characters.formUnion(.urlFragmentAllowed)
return characters
}
}
接下来,使用对 URL 进行编码的方法扩展 String
:
extension String {
/// Converts a string to a percent-encoded URL, including Unicode characters.
///
/// - Returns: An encoded URL if all steps succeed, otherwise nil.
func encodedUrl() -> URL? {
// Remove preexisting encoding,
guard let decodedString = self.removingPercentEncoding,
// encode any Unicode characters so URLComponents doesn't choke,
let unicodeEncodedString = decodedString.addingPercentEncoding(withAllowedCharacters: .urlAllowedCharacters),
// break into components to use proper encoding for each part,
let components = URLComponents(string: unicodeEncodedString),
// and reencode, to revert decoding while encoding missed characters.
let percentEncodedUrl = components.url else {
// Encoding failed
return nil
}
return percentEncodedUrl
}
}
可以像这样测试:
let urlText = "https://www.example.com/폴더/search?q=123&foo=bar&multi=eggs+and+ham&hangul=한글&spaced=lovely%20spam&illegal=<>#top"
let url = encodedUrl(from: urlText)
末尾的 url
值:https://www.example.com/%ED%8F%B4%EB%8D%94/search?q=123&foo=bar&multi=eggs+and+ham&hangul=%ED%95%9C%EA%B8%80&spaced=lovely%20spam&illegal=%3C%3E#top
请注意,保留 %20
和 +
间距,对 Unicode 字符进行编码,原始 urlText
中的 %20
不是双重编码的,并且锚点(片段或 #
)保留。
编辑:现在检查每个组件的有效性。
对于 Swift 5 来结束编码字符串
func escape(string: String) -> String {
let allowedCharacters = string.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: ":=\"#%/<>?@\\^`{|}").inverted) ?? ""
return allowedCharacters
}
如何使用 ?
let strEncoded = self.escape(string: "http://www.edamam.com/ontologies/edamam.owl#recipe_e2a1b9bf2d996cbd9875b80612ed9aa4")
print("escapedString: \(strEncoded)")
我自己也需要这个,所以我写了一个字符串扩展,它既允许 URLEncoding 字符串,也允许更常见的最终目标,将参数字典转换为“GET”样式的 URL 参数:
extension String {
func URLEncodedString() -> String? {
var escapedString = self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
return escapedString
}
static func queryStringFromParameters(parameters: Dictionary<String,String>) -> String? {
if (parameters.count == 0)
{
return nil
}
var queryString : String? = nil
for (key, value) in parameters {
if let encodedKey = key.URLEncodedString() {
if let encodedValue = value.URLEncodedString() {
if queryString == nil
{
queryString = "?"
}
else
{
queryString! += "&"
}
queryString! += encodedKey + "=" + encodedValue
}
}
}
return queryString
}
}
享受!
&
或 =
。请检查我的解决方案。
这个对我有用。
func stringByAddingPercentEncodingForFormData(plusForSpace: Bool=false) -> String? {
let unreserved = "*-._"
let allowed = NSMutableCharacterSet.alphanumericCharacterSet()
allowed.addCharactersInString(unreserved)
if plusForSpace {
allowed.addCharactersInString(" ")
}
var encoded = stringByAddingPercentEncodingWithAllowedCharacters(allowed)
if plusForSpace {
encoded = encoded?.stringByReplacingOccurrencesOfString(" ", withString: "+")
}
return encoded
}
我从这个链接找到了上面的函数:http://useyourloaf.com/blog/how-to-percent-encode-a-url-string/。
let Url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")
帮助我的是我创建了一个单独的 NSCharacterSet
并将其用于 UTF-8 编码的字符串,即 textToEncode 以生成所需的结果:
var queryCharSet = NSCharacterSet.urlQueryAllowed
queryCharSet.remove(charactersIn: "+&?,:;@+=$*()")
let utfedCharacterSet = String(utf8String: textToEncode.cString(using: .utf8)!)!
let encodedStr = utfedCharacterSet.addingPercentEncoding(withAllowedCharacters: queryCharSet)!
let paramUrl = "https://api.abc.eu/api/search?device=true&query=\(escapedStr)"
这些答案都不适合我。当 url 包含非英文字符时,我们的应用程序崩溃了。
let unreserved = "-._~/?%$!:"
let allowed = NSMutableCharacterSet.alphanumeric()
allowed.addCharacters(in: unreserved)
let escapedString = urlString.addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)
根据您尝试执行的参数,您可能只想创建自己的字符集。以上允许使用英文字符,并且 -._~/?%$!:
斯威夫特 4.2
有时发生这种情况只是因为 slug 中有空间或缺少通过 API URL 传递的参数的 URL 编码。
let myString = self.slugValue
let csCopy = CharacterSet(bitmapRepresentation: CharacterSet.urlPathAllowed.bitmapRepresentation)
let escapedString = myString!.addingPercentEncoding(withAllowedCharacters: csCopy)!
//always "info:hello%20world"
print(escapedString)
注意:不要忘记探索 bitmapRepresentation
。
版本:斯威夫特 5
// space convert to +
let mstring = string.replacingOccurrences(of: " ", with: "+")
// remove special character
var allowedQueryParamAndKey = NSCharacterSet.urlQueryAllowed
allowedQueryParamAndKey.remove(charactersIn: "!*'\"();:@&=+$,/?%#[]%")
return mstring.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey) ?? mstring
Swift 5 如果你想像下面这样编码字符串,你可以尝试 .afURLQueryAllowed 选项
let testString = "6hAD9/RjY+SnGm&B"
let escodedString = testString.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed)
print(escodedString!)
//编码后的字符串就像 en6hAD9%2FRjY%2BSnGm%26B
stringByAddingPercentEncodingWithAllowedCharacters()
毫无疑问它的作用。考虑到“惊讶”这个词有多长,有趣的评论。&
添加到URLQueryAllowedCharacterSet
的字符集中,并对每个字符进行了编码。检查了 iOS 9,看起来像错误,我选择了@bryanchen 的答案,效果很好!URLComponents
和URLQueryItem
的答案更清晰 IMO。