Apple官方的文档:
Return ValueAn NSString object initialized by converting the bytes in data into Unicode characters using encoding The returned object may be different from the original receiver Returns nil if the initialization fails for some reason (for example if data does not represent valid data for encoding)
返回nil很可能是编码问题, 有可能你的页面里混入了非utf8的字符
解决办法:
用libiconv清除非utf8字符
先给项目Link Binaries With Library 添加libiconvdylib
#include "iconvh"- (NSData )cleanUTF8:(NSData )data {
iconv_t cd = iconv_open("UTF-8", "UTF-8"); // 从utf8转utf8
int one = 1;
iconvctl(cd, ICONV_SET_DISCARD_ILSEQ, &one); // 丢弃不正确的字符
size_t inbytesleft, outbytesleft;
inbytesleft = outbytesleft = datalength;
char inbuf = (char )databytes;
char outbuf = malloc(sizeof(char) datalength);
char outptr = outbuf;
if (iconv(cd, &inbuf, &inbytesleft, &outptr, &outbytesleft)
== (size_t)-1) {
NSLog(@"this should not happen, seriously");
return nil;
}
NSData result = [NSData dataWithBytes:outbuf length:datalength - outbytesleft];
iconv_close(cd);
free(outbuf);
return result;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)