如何以查询字符串格式URL/param 1/param 2/param 3对URL参数进行UTF8编码我甚至尝试过URLHostAllowedCharacterSet,它编码特殊字符,但不编码“+”字符。如何使用almofire请求编码包含+字符的电子邮件?
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()!
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
2条答案
按热度按时间suzh9iv81#
尝试添加一个扩展来处理编码,然后在需要编码时调用该扩展。
然后使用它:
vwoqyblh2#