iOS开发中NSString与NSData相互转码?网址编码?

2017-03-09  本文已影响459人  随心吧
『导言』

iOS开发中,对于请求网络数据时候,经常需要处理编码转码问题?经常出现NSUTF8StringEncoding字样,在NSData和NSString的转换中如何用?


  • 编码: 使汉字** →** 含%的字符串
NSString *nameStr = [[NSString alloc]init];
nameStr = [nameStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *transString = [NSString stringWithString:[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  • str转datainitWithData: encoding:
NSString *str = @"username=zwj&pwd=123&type=JSON";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *str2 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  • str转str: stringByAddingPercentEscapesUsingEncoding:
NSString *str = @"http://120.25.226.186:32812/login2?username=文娟&pwd=520it&type=JSON";
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  • GET请求:
*  若url的`路径参数`含有`汉字`,需要`转码`;
 * 例1:参数中含有`汉字`为`小码哥`
   NSString *str = @"http://120.25.226.186:32812/login2?username=小码哥&pwd=520it&type=JSON";
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = [@"username=小码哥&pwd=520it&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
  • strdata
initWithData:  encoding:
  • datastr
dataUsingEncoding:
 > * `str`转`str`:
stringByAddingPercentEscapesUsingEncoding:
图.开心一刻

<1>.NSSData和NSString的相互转换
<2>.iOS开发中,如何转码字符串NSString或者网址str?

上一篇下一篇

猜你喜欢

热点阅读