有时我们需要将NSString转换为UTF-8,前几天发现苹果弃用了以前的旧接口,下面是查找了一些资料后,整理的代码
/**
* 编码
*/
NSString *url=@"http://www.jianshu.com/u/7be4a0163a7f?p1=%+&sd &p2=中文";
// 旧方法
NSString *encodedValue = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", encodedValue);
// 新方法
NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:url] invertedSet];
NSString *encodedUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
NSLog(@"%@", encodedUrl);
/**
* 解码
*/
// 旧方法
NSString *unencodedValue = [encodedValue stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", unencodedValue);
// 新方法
NSString *unencodeUrl = [encodedUrl stringByRemovingPercentEncoding];
NSLog(@"%@", unencodeUrl);
网友评论