Apple官方的文档:
|
Return Value
An 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 添加libiconv.dylib
#include "iconv.h"
- (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 = data.length;
char *inbuf = (char *)data.bytes;
char *outbuf = malloc(sizeof(char) * data.length);
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:data.length - outbytesleft];
iconv_close(cd);
free(outbuf);
return result;
}