URL編碼
api接口文檔,iOS7及以上可用:
- (nullable NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
@property (class, readonly, copy) NSCharacterSet *URLQueryAllowedCharacterSet API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
例子:
NSString *string = @"漢字666";
NSString *encodeString = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
兼容iOS7以下的api:
- (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc API_DEPRECATED("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.", macos(10.0,10.11), ios(2.0,9.0), watchos(2.0,2.0), tvos(9.0,9.0));
例子:
NSString *string = @"漢字666";
NSString *encodeString = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
URL解碼
api接口文檔,iOS7及以上可用:
@property (nullable, readonly, copy) NSString *stringByRemovingPercentEncoding API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
例子:
NSString *decodeString = encodeString.stringByRemovingPercentEncoding;
兼容iOS7以下的api:
- (nullable NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)enc API_DEPRECATED("Use -stringByRemovingPercentEncoding instead, which always uses the recommended UTF-8 encoding.", macos(10.0,10.11), ios(2.0,9.0), watchos(2.0,2.0), tvos(9.0,9.0));
例子:
NSString *decodeString = [encodeString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
總結
很多文章都說上面的URL編解碼新api在iOS 9.0以上使用,其實他們可能看到9.0就以爲iOS 9.0以上才能使用,或者看到老api9.0以上不能用就反推新api再iOS 9.0以上纔可用,其實蘋果文檔裏寫的新api是tvos(9.0)?,而ios是7.0。所以,看文檔要仔細哦?,以官方文檔爲準。