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

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

这里写图片描述

阅读更多
版权声明:随便转载,方便就写个出处。 https://blog.csdn.net/xiao562994291/article/details/78100419
个人分类: IOS
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭