如何编码'' +' url字符串中的字符?

时间:2017-01-17 12:50:26

标签: ios swift url swift3

我想在我的网址字符串中对 + 字符进行编码,我尝试这样做:

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

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

但这不适用于 +

任何想法?感谢。

更新

网址中的type=参数更具动态性,我不会对 + 字符做一些隐含的替换。此type=参数表示UITextField值,因此可以输入任何内容。

我也很好奇为什么addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)在这种特殊情况下不会工作?

3 个答案:

答案 0 :(得分:6)

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

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

输出:

  

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

答案 1 :(得分:2)

将%替换为%2B

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

答案 2 :(得分:0)

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://stackoverflow.com/a/24552028/8642838