如何在 URL 字符串中编码“+”字符?

5

我想在我的URL字符串中编码+字符,我尝试用以下方式实现:

let urlString = "www.google.com?type=c++"

let result = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

但是这对于+无效。有什么想法吗?谢谢。
更新:
此外,url中的type=参数是动态的,我不会对+字符进行一些隐含的替换。该type=参数表示一个UITextField值,因此可以输入任何内容。
我也很好奇为什么在这种特殊情况下addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)无法工作?

你可以使用 urlString.replaceOccurrences(of: "+", with:"") 吗? - Mr. Xcoder
请查看这个链接 - OOPer
请阅读更新。在这种情况下,我不会替换字符。 - Robert
1
它不会起作用,因为“+”是“url查询字符串”的有效字符,它是“[空格]”的“url编码”版本。 - user28434'mstep
好的,谢谢你的回答 :) - Robert
3个回答

7
let allowedCharacterSet = CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted

if let escapedString = "www.google.com?type=c++".addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) {
  print(escapedString)
}

Output:

www.google.com%3Ftype%3Dc%2B%2B


1
是的,你的方法足够好(不是最理想的),但我很好奇为什么 addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) 不起作用... - Robert
1
这是我无法回答的问题,他们可能有很好的理由没有加上 + - Viktor Gardart

3

Swift 5

使用扩展并将加号添加到不允许的字符中,这样您就可以创建自己的字符集并在需要时重复使用它:

extension CharacterSet {
    
    /// Characters valid in part of a URL.
    ///
    /// 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 {
        // You can extend any character set you want
        var characters = CharacterSet.urlQueryAllowed
        characters.subtract(CharacterSet(charactersIn: "+"))
        return characters
    }
}

使用方法:

let urlString = "www.google.com?type=c++"

let result = urlString.addingPercentEncoding(withAllowedCharacters: .urlAllowedCharacters)

我找到了一个包含 URL 编码字符集的列表。 以下是有用的(反转的)字符集:

URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

来源:https://dev59.com/RWAf5IYBdhLWcg3wgzHI#24552028


1

用 %2B 替换 +

let urlString = "www.google.com?type=c++"
let newUrlString = aString.replacingOccurrences(of: "+", with: "%2B")

你的方法是我最不想用的。 - Robert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接