(1) 因为url支持26个英文字母、数字和少数几个特殊字符,因此,对于url中包含非标准url的字符时(比如有汉字时),就需要对其进行编码。iOS中提供了函数stringByAddingPercentEscapesUsingEncoding对中文和一些特殊字符进行编码,但是stringByAddingPercentEscapesUsingEncoding的功能并不完善,对一些较为特殊的字符无效。而对这些字符则可以使用CFURLCreateStringByteAddingPercentEscapes函数,
1 NSString *str = [NSString stringWithUTF8String:surl.c_str()]; 2 str = @”http://218.21.213.10/MobileOA/TIFF/鄂安办发45号关于下达2012年全市安全生产相对控制指标的通知1.jpg”; 3 str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
(2) stringByAddingPercentEscapesUsingEncoding用与将Unicode字符转换成有百分号的形式。 stringByReplacingPercentEscapesUsingEncoding:将百分号形式转换成Unicode形式 例子: NSString *rawText = @”One Broadway, Cambridge, MA”; NSString *encodedText = [rawText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@”Encoded text: %@”, encodedText); NSString decodedText = [encodedText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@”Original text: %@”, decodedText); 输出: Encoded text: One%20Broadway,%20Cambridge,%20MA
Original text: One Broadway, Cambridge, MA ********************************************* stringByAddingPercentEscapesUsingEncoding对中文和一些特殊字符进行编码,但是stringByAddingPercentEscapesUsingEncoding的功能并不完善,对一些像& /等特殊的字符无效。而对这些字符则可以使用CFURLCreateStringByteAddingPercentEscapes函数, 例子: // Encode a string to embed in an URL. NSString encodeToPercentEscapeString(NSString string) { return (NSString ) CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef) string, NULL, (CFStringRef) @”!’();:@&=+$,/?%#[]”, kCFStringEncodingUTF8); }
// Decode a percent escape encoded string. NSString decodeFromPercentEscapeString(NSString *string) { return (NSString *) CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef) string, CFSTR(“”), kCFStringEncodingUTF8); }
int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *rawText = @”Bed Bath & Beyond - URL=http://www.bedbathandbeyond.com/“;
NSString *encodedText = encodeToPercentEscapeString(rawText); NSLog(@”Encoded text: %@”, encodedText); NSString *decodedText = decodeFromPercentEscapeString(encodedText); NSLog(@”Original text: %@”, decodedText);
[pool drain]; return 0; }