您的位置:首页 > 移动开发 > Objective-C

Objective-C 对 URL 进行 URLEncode 编码

2012-05-03 11:43 288 查看
//使用到的函数原型
- (NSUInteger)replaceOccurrencesOfString:(NSString *)target
withString:(NSString *)replacement
options:(NSStringCompareOptions)opts
range:(NSRange)searchRange;

CFStringRef CFURLCreateStringByAddingPercentEscapes(CFAllocatorRef allocator,
CFStringRef originalString,
CFStringRef charactersToLeaveUnescaped,
CFStringRef legalURLCharactersToBeEscaped,
CFStringEncoding encoding);
/**
* URL encodes a string
*/
- (NSString*)stringByURLEncodingStringParameter;

//.m
- (NSString*)stringByURLEncodingStringParameter
{
// NSURL's stringByAddingPercentEscapesUsingEncoding: does not escape
// some characters that should be escaped in URL parameters, like / and ?;
// we'll use CFURL to force the encoding of those
//
// We'll explicitly leave spaces unescaped now, and replace them with +'s
//
// Reference: <a href="%5C%22http://www.ietf.org/rfc/rfc3986.txt%5C%22" target="\"_blank\"" onclick='\"return' checkurl(this)\"="" id="\"url_2\"">http://www.ietf.org/rfc/rfc3986.txt</a>

NSString *resultStr = self;

CFStringRef originalString = (CFStringRef) self;
CFStringRef leaveUnescaped = CFSTR(" ");
CFStringRef forceEscaped = CFSTR("!*'();:@&=+$,/?%#[]");

CFStringRef escapedStr;
escapedStr = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
originalString,
leaveUnescaped,
forceEscaped,
kCFStringEncodingUTF8);

if( escapedStr )
{
NSMutableString *mutableStr = [NSMutableString stringWithString:(NSString *)escapedStr];
CFRelease(escapedStr);

// replace spaces with plusses
[mutableStr replaceOccurrencesOfString:@" "
withString:@"%20"
options:0
range:NSMakeRange(0, [mutableStr length])];
resultStr = mutableStr;
}
return resultStr;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息