字节转换[]以NSData的后数据损坏(Data corrupt after converting

2019-08-17 20:12发布

I have .Net web service response containing a byte[] entry, among other fields. The data is a PDF file.

I extract the Dictionary from the received data with: [NSJSONSerialization JSONObjectWithData]

Hereafter I use the following code to convert the byte[] to NSData. I then save the result to disk (see last line).

When opening the resulting PDF file, I get the following error:

"failed to find PDF header: `%PDF' not found."

        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"]];

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.

** When pulling multiple PDF asynchronously at the same time, some of these reports received as base64 strings were also corrupted.

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.

Edit: 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.

Thank you!

Answer 1:

好了,经过细齿梳我的代码(如从启发snadeep.gvn终于整理了这一点http://www.raywenderlich.com/forums/viewtopic.php?f=2&p=38590#p38590 )。

我犯了一个愚蠢的错误,我忽略了100+次。

此行的代码:

NSData* data = [NSData dataWithBytes:(const void *)byteArray length:sizeof(unsigned char)*c];

应更改为:

NSData* data = [NSData dataWithBytes:(const void *)bytes length:sizeof(unsigned char)*c];

好时光,现在我终于可以睡个安稳觉:-)



文章来源: Data corrupt after converting byte[] to NSData