@interfaceNSString (NSURLUtilities)
// Returns a new string made from the receiver by replacing all characters not in the allowedCharacters set with percent encoded characters. UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded. This method is intended to percent-encode an URL component or subcomponent string, NOT the entire URL string. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.
- (nullableNSString*)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet*)allowedCharactersNS_AVAILABLE(10_9,7_0);
// Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters.
@property(nullable,readonly,copy)NSString*stringByRemovingPercentEncodingNS_AVAILABLE(10_9,7_0);
- (nullableNSString*)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encNS_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.");
- (nullableNSString*)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encNS_DEPRECATED(10_0,10_11,2_0,9_0,"Use -stringByRemovingPercentEncoding instead, which always uses the recommended UTF-8 encoding.");
@end
使用如下:
(NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
只要传入相应的编码即可以进行编码和解码了,不过此方法是对整个Url进行编码的所以如果有Query String中带有&?/等是不会进行编码转换的,如果有这方面的需要的朋友可以参照下面提供的网址,找到解决方法:http://www.cocoachina.com/bbs/read.php?tid-2469.html
示例:
[cpp]view plaincopy
NSString* string1 = @"https://www.cloudsafe.com/文件夹";
NSString* string2 = [string1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string3 = [string2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string4 = [string2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string5 = [string3 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string6 = [string4 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string7 = [string5 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
输出结果: string5 & 6 重复编码encode
string1:https://www.cloudsafe.com/文件夹
string2:https://www.cloudsafe.com/%E6%96%87%E4%BB%B6%E5%A4%B9
string3:https://www.cloudsafe.com/%25E6%2596%2587%25E4%25BB%25B6%25E5%25A4%25B9
string4:https://www.cloudsafe.com/文件夹
string5:https://www.cloudsafe.com/%E6%96%87%E4%BB%B6%E5%A4%B9
string6:https://www.cloudsafe.com/文件夹