27
2017
09

iOS NSData 转 NSString为空

如果转换失败,可能是data里面包含了非UTF-8字符。

 NSMutableString *string = [[NSMutableString alloc]     initWithData:data encoding:NSUTF8StringEncoding];
    if (!string) {
        string = [[NSMutableString alloc]initWithData:[self cleanUTF8:data] encoding:NSUTF8StringEncoding];
    }

清除非UTF-8字符。

1. Linked Frameworks and Libraries 添加 libiconv.tbd。

2. 添加头文件

#import <iconv.h>

3. 复制代码,粘贴到项目中

/** 剔除非UTF-8字符  @param data 原来的数据data  @return 处理后的输入data */
- (NSData *)cleanUTF8:(NSData *)data {
    iconv_t cd = iconv_open("UTF-8", "UTF-8"); // 从UTF-8转UTF-8
    int one = 1;
    iconvctl(cd, ICONV_SET_DISCARD_ILSEQ, &one); // 剔除非UTF-8的字符

    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;
}

悦览播放器 一个好用的视频音频播放软件

这里写图片描述

上一篇:APP登录界面(网页仿制版) 下一篇:STC89C51单片机串口程序下载失败总结