iOS / swift中的UTF8编码,适用于包含+的电子邮件

vfh0ocws  于 2023-02-01  发布在  iOS
关注(0)|答案(2)|浏览(110)

如何以查询字符串格式URL/param 1/param 2/param 3对URL参数进行UTF8编码
我甚至尝试过URLHostAllowedCharacterSet,它编码特殊字符,但不编码“+”字符。
如何使用almofire请求编码包含+字符的电子邮件?

suzh9iv8

suzh9iv81#

尝试添加一个扩展来处理编码,然后在需要编码时调用该扩展。

extension String {
    func stringByAddingPercentEncodingForRFC3986() -> String? {
        let unreserved = "-._~/?:"
        let allowed = NSMutableCharacterSet.alphanumericCharacterSet()
        allowed.addCharactersInString(unreserved)
        return stringByAddingPercentEncodingWithAllowedCharacters(allowed)
    }
}

然后使用它:

let query = "http://test.com/param1& param2+ param3"
let encoded = query.stringByAddingPercentEncodingForRFC3986()!
vwoqyblh

vwoqyblh2#

extension String {
  func stringByAddingPercentEncodingForRFC3986() -> String? {
    let unreserved = "-._~/?:"
    let allowedCharacterSet = NSMutableCharacterSet.alphanumeric()
    allowedCharacterSet.addCharacters(in: unreserved)
    return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet)
  }
}

let encodedVal = usernameTextField.text.stringByAddingPercentEncodingForRFC3986()
  • ------或----------
extension String {
   var urlEncoded: String? {
    let allowedCharacterSet = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~/?:"))
    return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)
  }
}

let encodedVal = usernameTextField.text.urlEncoded

相关问题