简体   繁体   中英

Data corrupt after converting byte[] to NSData

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!

Ok, 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 ).

I made a stupid mistake, which I overlooked 100+ times.

This line of code:

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

Should change to:

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

Good times, now I can finally get some sleep :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM