1
votes

I'm trying to transmit a zip archive between a server and a device, and I'm trying to figure out what I'm doing wrong. To make life easy, I've currently uploaded the file using PHPMyAdmin's upload features in an effort to reduce possible encoding issues. I've also confirmed that the file in the database is correct by creating a quick script that serves it up as a download -- other than having to rename the file to a .zip file (because I didn't specify a filename), it works perfectly.

The server uses the following code to serve up the zipped data. ($ad is an object, with getZippedHTML() doing exactly what it sounds like: it recovers the actual binary data) I use UTF8 encoding to avoid an issue where json_encode won't print direct binary data for an unkown.

$response['ad']=utf8_encode($ad->getZippedHTML();
print  json_encode($response);

On the iOS side, I attempt to decode the data with:

NSString *zipString=[serverResponse valueForKey:@"ad"];
NSData *zipData=[zipString dataUsingEncoding:NSUTF8StringEncoding];
//Test retrieved data
[zipData writeToFile:zipPath atomically:YES];

However, the file that gets written to disk doesn't appear to be a valid zip archive -- unzip utilities are unable to use it. I've tracked down the issue to the fact that I'm not decoding the data with dataUsingEncoding, but rather encoding it all over again.

How do I take a UTF8 encoded string and reverse that to NSData?

1

1 Answers

0
votes

You might try:

- (BOOL)getBytes:(void *)buffer maxLength:(NSUInteger)maxBufferCount 
    usedLength:(NSUInteger *)usedBufferCount encoding:(NSStringEncoding)encoding 
    options:(NSStringEncodingConversionOptions)options range:(NSRange)range 
    remainingRange:(NSRangePointer)leftover

Passing a C pointer to the buffer. You can get the length of the data given the encoding with the method:

- (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc

You can then create an NSData object with:

+ (id)dataWithBytes:(const void *)bytes length:(NSUInteger)length

There might be a more convenient means of accomplishing this, but I believe these methods will get you where you want to go.