ios中url經(jīng)常需要進行encode巾遭、decode處理,廢話不多平道,直接高清無碼睹欲,直逼問題!!窘疮!
第一種:比較陳舊
//URLEncode
+ (NSString*) encodeString:(NSString*)unencodedString {
// CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
// CharactersToLeaveUnescaped = @"[].";
NSString *encodedString = (NSString *)
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8));
return encodedString;
}
//URLDEcode
-(NSString *)decodeString:(NSString*)encodedString
{
//NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
NSString *decodedString = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
(__bridge CFStringRef)encodedString,
CFSTR(""),
CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
return decodedString;
}
第二種:ios7.0之后
//encode
[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//decode
[string stringByRemovingPercentEncoding];
第三種:自定義
NSCharacterSet`系統(tǒng)內(nèi)置的一些返回CharacterSet 的方法
- URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
- URLHostAllowedCharacterSet "#%/<>?@\^`{|}
- URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}
- URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
- URLQueryAllowedCharacterSet "#%<>[\]^`{|}
- URLUserAllowedCharacterSet "#%/:<>?@[\]^`
NSCharacterSet *chaSet = [NSCharacterSet characterSetWithCharactersInString:@"'();:@&=+$,/?%#[]"];
[string stringByAddingPercentEncodingWithAllowedCharacters:chaSet];