将byte []转换为NSData后数据损坏 [英] Data corrupt after converting byte[] to NSData
问题描述
我的.Net Web服务响应包含byte []条目,以及其他字段。
数据是PDF文件。
I have .Net web service response containing a byte[] entry, among other fields. The data is a PDF file.
我从收到的数据中提取字典:
[NSJSONSerialization JSONObjectWithData]
I extract the Dictionary from the received data with: [NSJSONSerialization JSONObjectWithData]
此后我使用以下代码将byte []转换为NSData。
然后我将结果保存到磁盘(参见最后一行)。
Hereafter I use the following code to convert the byte[] to NSData. I then save the result to disk (see last line).
打开生成的PDF文件时,出现以下错误:
When opening the resulting PDF file, I get the following error:
找不到PDF标题:找不到'%PDF'。
NSArray *byteArray = [rootDictionary objectForKey:@"file"];
unsigned c = byteArray.count;
uint8_t *bytes = malloc(sizeof(*bytes) * c);
unsigned i;
for (i = 0; i < c; i++)
{
NSString *str = [byteArray objectAtIndex:i];
int byte = [str intValue];
bytes[i] = (uint8_t)byte;
}
NSData* data = [NSData dataWithBytes:(const void *)byteArray length:sizeof(unsigned char)*c];
//Save to disk using svc class.
NSString *localPath = [svc saveReport:data ToFile:[rootDictionary objectForKey:@"name"]];
我也尝试将byte []转换为base64 NSString(在服务端)然后返回在我的应用程序中的NSData,它工作(**大多数)但我被告知它是邋code的代码。
I also tried converting the byte[] to a base64 NSString (on the service side) and then back to NSData in my app, which worked (**mostly) but I was told that it's sloppy code.
**当同时异步拉出多个PDF时,有些收到的这些报告作为base64字符串也已损坏。
** When pulling multiple PDF asynchronously at the same time, some of these reports received as base64 strings were also corrupted.
PS。如果我必须提供我的svc课程的代码,请告诉我,但我认为问题不存在。
PS. Please let me know if I must supply the code from my svc class as well, but I don't think the problem is there.
编辑:
我创建了一个新的Web服务方法,它接受一个byte []作为输入,然后修改我的iOS应用程序将byteArray变量发送回服务,然后将其保存到文件中。
生成的PDF文件是Adobe可读的有效文件。意思是转移期间没有腐败。
I created a new web service method which takes a byte[] as input, then modified my iOS app to send the byteArray variable back to the service, where it get's saved to a file. The resulting PDF file is a valid file readable by Adobe. Meaning there is no corruption during transfer.
谢谢!
推荐答案
好的,最后在对我的代码进行精细梳理后对其进行了整理(受到来自 http://www.raywenderlich.com/forums/viewtopic.php?f=2&p=38590#p38590 )。
O.k, finally sorted this out after fine-tooth-combing my code (as inspired by snadeep.gvn from http://www.raywenderlich.com/forums/viewtopic.php?f=2&p=38590#p38590).
我犯了一个愚蠢的错误,我忽略了100多次。
I made a stupid mistake, which I overlooked 100+ times.
这行代码:
NSData* data = [NSData dataWithBytes:(const void *)byteArray length:sizeof(unsigned char)*c];
应更改为:
NSData* data = [NSData dataWithBytes:(const void *)bytes length:sizeof(unsigned char)*c];
好时光,现在我终于可以睡一觉了: - )
Good times, now I can finally get some sleep :-)
这篇关于将byte []转换为NSData后数据损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!