使用 initWithBytes:length:encoding 将 NSData 转换为 NSString
我想从 iPhone 应用程序发送一些图像数据 (jpeg) 到我的网络服务。为了做到这一点,我使用图像中的 NSData 并将其转换为一个字符串,该字符串将放置在我的 JSON 中。
目前,我正在这样做:
NSString *secondString = [[NSString alloc] initWithBytes:[result bytes]
length:[result length]
encoding:NSUTF8StringEncoding];
其中结果是 NSData 类型。但是,即使结果长度返回实际值(如 14189),secondString 也显示为 null。我使用这种方法是因为结果是原始数据并且不是空终止的。
我做错了什么吗?我已经在其他领域使用过这段代码,它似乎工作得很好(但我当前使用它的那些领域涉及文本而不是图像数据)。
TIA。
I have some image data (jpeg) I want to send from my iPhone app to my webservice. In order to do this, I'm using the NSData from the image and converting it into a string which will be placed in my JSON.
Currently, I'm doing this:
NSString *secondString = [[NSString alloc] initWithBytes:[result bytes]
length:[result length]
encoding:NSUTF8StringEncoding];
Where result is of type NSData. However, secondString appears to be null even though result length returns a real value (like 14189). I used this method since result is raw data and not null-terminated.
Am I doing something wrong? I've used this code in other areas and it seems to work fine (but those areas I'm currently using it involve text not image data).
TIA.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于二进制数据,最好使用 Base64 编码对其进行编码,然后在 Web 服务中对其进行解码。我使用从 此处下载的 NSData+Base64 类,此参考资料也取自 Stackoverflow,@Ken 所做的答案 (谢谢肯!)。
For binary data, better to encode it using Base64 encoding then decode it in you webservice. I use NSData+Base64 class downloaded from here, this reference was also taken from Stackoverflow, an answer made by @Ken (Thanks Ken!).
您没有将数据转换为字符串。您尝试将其解释为 UTF-8 编码的字符串,除非数据确实是 UTF-8 编码的字符串,否则该操作将会失败。最好的选择是以某种方式对其进行编码,也许像 Manny 建议的那样使用 Base64,然后在服务器上再次对其进行解码。
You are not converting the data to a string. You are attempting to interpret it as a UTF-8 encoded string, which will fail unless the data really is a UTF-8 encoded string. Your best bet is to encode it somehow, perhaps with Base64 as Manny suggests, and then decode it again on the server.