IOSURL中⽂乱码问题解决⽅案
IOS 解决URL中⽂乱码问题解决
在做⼀个HTTPS连接时, 要客户端合成⼀段HTTPS地址
如果地址含中⽂的话程序会crash, 检查发现原来是中⽂没有转码的原因
在NSString库⾥⾯到了下⾯两个⽅法
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
试了下, 有效
NSString* string1 = @"www.cloudsafe/⽂件夹";
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];
输出string1-7结果如下
string1:www.cloudsafe/⽂件夹
string2:www.cloudsafe/%E6%96%87%E4%BB%B6%E5%A4%B9
string3:www.cloudsafe/%25E6%2596%2587%25E4%25BB%25B6%25E5%25A4%25B9
string4:www.cloudsafe/⽂件夹
string5:www.cloudsafe/%E6%96%87%E4%BB%B6%E5%A4%B9
string6:www.cloudsafe/⽂件夹
string7:www.cloudsafe/⽂件夹
简单说下我是如何使⽤的:
在合成URL后, 给整个String转码两次
NSMutableString *address = [[NSMutableString stringWithString:SetNiChengStringWithoutUserNameAndNiCheng] mutableCopy];  address = [[address stringByAppendingString:app.name] mutableCopy];
address = [[address stringByAppendingString:@"/"] mutableCopy];
url编码处理
address = [[address stringByAppendingString:_] mutableCopy];
address = [[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy];
address = [[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy];
服务器端如何只是简单存储, 服务器接收数据后可以不⽤转码成中⽂
当客户端请求这部分数据时, 由客户端⾃⼰解码就好了
获取到字串后解码⼀次就可以正常显⽰为中⽂了:
str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
感谢阅读,希望能帮助到⼤家,谢谢⼤家对本站的⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。