1.URL编码
NSString *encodeURL = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
2.URL解码
NSString *decodeURL = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
ios 9.0中已经替换此方法
NSString *encodedURL = [url stringByAddingPercentEncodingWithAllowedCharacters:(nonnull NSCharacterSet *)];
NSString *decodedURL = [url stringByRemovingPercentEncoding];
- (NSString )stringByAddingPercentEscapesUsingEncodingExt:(NSStringEncoding)enc stringWith:(NSString )str
{
if([str respondsToSelector:@selector(stringByAddingPercentEncodingWithAllowedCharacters:)] == YES)
{
NSCharacterSet set = [[NSCharacterSet characterSetWithCharactersInString:@"!'();:@&=+$,/?%#[]"] invertedSet];
return [str stringByAddingPercentEncodingWithAllowedCharacters:set];
}
else
{
pragma clang diagnostic push
pragma clang diagnostic ignored "-Wdeprecated-declarations"
// NSString * newString = (__bridge_transfer NSString *)
NSString * newString = ( NSString *)
CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef)str,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
CFStringConvertNSStringEncodingToEncoding(enc));
pragma clang diagnostic pop
return newString;
}
}