我正在使用以下方法在目标 - C 中对字符串进行编码:
+(NSString*)urlEncoded:(NSString*)string
{ return ((NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes (NULL,(CFStringRef)string, NULL,(CFStringRef)@"! '=();@&+$%#",kCFStringEncodingUTF8 )));}
在 Swift 2.0 中是否有与此方法对应的方法?我已经尝试使用堆栈中存在的许多解决方案,但没有一个可以解决我的问题。
最佳答案
您可能希望将 stringByAddingPercentEncodingWithAllowedCharacters
与 NSCharacterSet
的 URL 组件特定字符集一起使用:
let title = "NSURL / NSURLComponents"
let escapedTitle = title.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
这些字符集背后的想法是,对于它们所描述的用途,它们可能比您拥有的任何有限集都更正确。也就是说,您可以对自己生成的集合使用相同的方法:
let escapeSet = NSCharacterSet(charactersInString: "! '=();@&+$%#")
let string = "sdfT&*w5e#sto([+peW7)%y9pqf])"
let escapedString = string.stringByAddingPercentEncodingWithAllowedCharacters(escapeSet.invertedSet)
// "sdfT%26*w5e%23sto%28[%2BpeW7%29%25y9pqf]%29"
关于ios - 字符串编码 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35215338/