使用 initWithBytes:length:encoding 将 NSData 转换为 NSString

发布于 2024-10-01 08:09:38 字数 558 浏览 0 评论 0原文

我想从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

因为看清所以看轻 2024-10-08 08:09:38

对于二进制数据,最好使用 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!).

七分※倦醒 2024-10-08 08:09:38

您没有将数据转换为字符串。您尝试将其解释为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文