我们知道,使用NSURLConnection的代理方法下载网页,存到一个NSData中,
<a target=_blank rel="nofollow" href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableData_Class/" style="text-decoration: none; color: rgb(147, 233, 202);">NSMutableData</a> *pageData;
[pageData appendData:data];
如果网页编码是UTF-8的,可以这么转换为字符串:
<a target=_blank rel="nofollow" href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/" style="text-decoration: none; color: rgb(147, 233, 202);">NSString</a> *pageSource = [[<a target=_blank rel="nofollow" href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/" style="text-decoration: none; color: rgb(147, 233, 202);">NSString</a> alloc] initWithData:pageData encoding:NSUTF8StringEncoding];
如果网页是gbk(或者gb2312),用UTF8转换的话,pageSource返回nil。这时需要使用gbk编码做转换,但是NSStringEncoding不含gbk,怎么办?用另一个方法处理一下:
<span style="color:#ff0000;"><strong>NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);</strong></span> <a target=_blank rel="nofollow" href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/" style="text-decoration: none; color: rgb(147, 233, 202);">NSString</a> *pageSource = [[<a target=_blank rel="nofollow" href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/" style="text-decoration: none; color: rgb(147, 233, 202);">NSString</a> alloc] initWithData:pageData encoding:<span style="color:#ff0000;"><strong>gbkEncoding</strong></span>];
为什么可以这么处理?在NSString.h(按住command,双击NSStringEncoding即能查看),对NSStringEncoding的定义中,注释这么写着:
<span style="white-space: normal;">Note that in addition to the values explicitly listed below, NSStringEncoding supports encodings provided by CFString.</span>
<span style="white-space: normal;">See CFStringEncodingExt.h for a list of these encodings.</span>
<span style="white-space: normal;">See CFString.h for functions which convert between NSStringEncoding and CFStringEncoding. ======================================================================================== 我要实现的是将我的ios端的数据通过php写的服务端写入到数据库中,由于要写入中文信息,我php端都是用的gbk编码,但是测试的时候数据库中写入的一直是乱码,也无法匹配中文。 后来发现是我ios端往php端发送数据是用的编码不对。我们知道在ios中设置data的编码时,<span style="color:#ff0000;"><strong>NSStringEncoding</strong></span>默认是没有gbk这些编码的,如图: </span>