如何只编码 PercentEncoding 中的所有特殊字符是 swift 5

How to encode only all special characters in PercentEncoding is swift 5

我是运行从Whosebug到percentage类似问题的代码只编码所有特殊字符(@!#$%^&*()~-_=+;:'/.,< >{}[])(不编码字母数字字符)在 xcode playground 上。这是我的尝试

          import UIKit
    
    //////////////
    //Attempt 1
    var originalString = "Test@123!#$%^&*()~-_=+;:'/.,<>{}[]"
    
    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
    
    print("Attemp 1:",escapedString)
    ///////////////////
    //Attempt 2
    func encodeValue(_ string: String) -> String? {
        guard let unescapedString = string.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: ":/").inverted) else { return nil }
    
        return unescapedString
    }
    
    let encodedString = encodeValue("Test@123!#$%^&*()~-_=+;:'/.,<>{}[]")
    print("Attemp 2:",encodedString)
    //////////////////////
    //Attempt 3
    extension String {
        var encoded: String? {
            return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        }
    }
    
    
    let encodedUrl = "Test@123!#$%^&*()~-_=+;:'/.,<>{}[]".encoded
    print("Attemp 3:",encodedUrl)
        //////////////
    //Attempt 4
    let myurlstring = "Test@123!#$%^&*()~-_=+;:'/.,<>{}[]"
    let urlwithPercentEscapes = myurlstring.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
    print("Attemp 4:",urlwithPercentEscapes)

//////////////
//Attempt 5
var s = "Test@123!#$%^&*()~-_=+;:'/.,<>{}[]"
let encodedLink = s.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)
let encodedURL = NSURL(string: encodedLink!)! as URL
print("Attemp 5:",encodedURL)

这是结果

Attemp 1: Optional("Test@123!%23$%25%5E&*()~-_=+;:'/.,%3C%3E%7B%7D%5B%5D")

Attemp 2: Optional("Test@123!#$%^&*()~-_=+;%3A'%2F.,<>{}[]")

Attemp 3: Optional("Test%40123!%23$%25%5E&*()~-_=+;%3A'%2F.,%3C%3E%7B%7D%5B%5D")

Attemp 4: Optional("Test@123!%23$%25%5E&*()~-_=+;:'/.,%3C%3E%7B%7D%5B%5D")

Attemp 5: Test@123!%23$%25%5E&*()~-_=+;:'/.,%3C%3E%7B%7D%5B%5D

他们中没有一个是对完整的特殊字符进行百分比编码characters.I想要对所有特殊字符进行编码,就像在几乎所有尝试中都没有对以下特殊字符进行编码一样。

*()~-_=+;:'/.,

请告诉我百分比编码我所有特殊字符的代码,包括 *()~-_=+;:'/., ?谢谢

要对除字母数字以外的所有内容进行百分比编码,请将 .alphanumerics 作为允许的字符传递:

let encoded = s.addingPercentEncoding(withAllowedCharacters: .alphanumerics)

对于您的示例,此 returns(作为可选):

Test%40123%21%23%24%25%5E%26%2A%28%29%7E%2D%5F%3D%2B%3B%3A%27%2F%2E%2C%3C%3E%7B%7D%5B%5D

我想这就是你要找的。

这不是特别有用,因为这不太可能正确编码任何特定的 URL(这似乎是您正在做的)。但是如果你有你描述的需求(这与正确编码 URLs 无关),那么你就是这样做的。

如果要正确编码 URL,请使用 URLComponents 构造 URL。它将使用该片段的规则对每个片段进行编码。没有简单的字符串替换可以正确地对 URL.

进行百分比编码