有的時候咱們會碰見字符串里有一些特殊字符在轉(zhuǎn)成URL的時候 會出現(xiàn)轉(zhuǎn)換不了的情況,這個時候需要對字符串進行編碼
9.0以前使用stringByAddingPercentEscapesUsingEncoding
9.0之后使用stringByAddingPercentEncodingWithAllowedCharacters
官方文檔這樣寫的
- (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc NS_DEPRECATED(10_0, 10_11, 2_0, 9_0, "Use -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.");
以下是轉(zhuǎn)碼demo:
NSString *resourcePath = @"http://www.baidu.com?tickets=[{\"num\":\"1\",\"priceId\":\"8a82824756\"}]";
NSString *encodePath ;
if (!IOS7_OR_LATER) {
encodePath = [resourcePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}else{
encodePath = [resourcePath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
}