有時(shí)我們需要將NSString轉(zhuǎn)換為UTF-8,前幾天發(fā)現(xiàn)蘋果棄用了以前的舊接口订晌,下面是查找了一些資料后澎剥,整理的代碼
/**
* 編碼
*/
NSString *url=@"http://www.reibang.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);