Objective-C学习——中文URL编码和解码
发现NSString类中有内置的方法可以实现。他们分别是:
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
只要传入相应的编码即可以进行编码和解码了,不过此方法是对整个Url进行编码的所以如果有Query String中带有&?/等是不会进行编码转换的,如果有这方面的需要的朋友可以参照下面提供的网址,找到解决方法:http://www.cocoachina.com/bbs/read.php?tid-2469.html
示例:
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/文件夹 string7:https://www.cloudsafe.com/文件夹
或者用
+(NSString*)encodeURIComponent:(NSString*)str{ return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)str, NULL, (__bridge CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))); }
iOS9废弃 这些方法已废弃, 用以下方法替换
NSString *urlString = @"http://www.3gbizhi.com/lists-全部/1.html"; //urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; //http://www.3gbizhi.com/lists-%E5%85%A8%E9%83%A8/1.html
相关推荐
84407518 2012-07-16
87214552 2015-10-27
84407518 2016-01-25
89283517 2012-06-19
ObjectiveC 2012-06-14
zhujiangtaotaise 2020-01-01
AllenG 2013-07-07
Beatopcoder 2013-07-14
afrtooylsw 2014-05-14
让编程改变世界 2015-03-13
shqhope 2015-04-09
zoutian00 2015-05-12
huangshm 2019-01-14
86981633 2019-06-29
我的iOS王者之路 2019-06-28
好好学习天天 2019-06-28