繁体   English   中英

字符串编码-Swift

[英]String encoding - Swift

我正在使用以下方法在目标-C中编码字符串:

+(NSString*)urlEncoded:(NSString*)string
{ return ((NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes (NULL,(CFStringRef)string, NULL,(CFStringRef)@"! '=();@&+$%#",kCFStringEncodingUTF8 )));}

Swift 2.0中是否有与此方法相对应的方法? 我尝试使用堆栈上存在的许多解决方案,但没有一个可以解决我的问题。

您可能想将stringByAddingPercentEncodingWithAllowedCharactersNSCharacterSet的特定于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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM