发现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%B9string3: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
总结 以上是内存溢出为你收集整理的Objective-C学习——中文URL编码和解码全部内容,希望文章能够帮你解决Objective-C学习——中文URL编码和解码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)