iPhone and GZip

2019-01-17 13:32发布

问题:

Now I know that xCode automaticly does the GZip decrompession for you within:

NSData *data = [NSData dataWithContentsOfURL:URL];

And it does work if I point to a Gzip file on my server. But since my content is dynamic, I have a PHP script that rather then create a gzip file like so:

$zp   = gzopen($file, "r");
$data = gzread($zp, $filesize);
gzclose($zp);

I encode my own data with:

echo gzencode($data, 9);

With this I add the following headers:

header("Content-Type: application/x-gzip");
header("Content-Encoding: gzip");
header("Accepts-Encoding: gzip");

When I browse to the URL, my browser wants to download the file automatically and I am able to unzip it on my Mac and view it's content. However when I try to read it through xCode it won't work.

NSData *data = [NSData dataWithContentsOfURL:URL];
NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog (content); //returns only data when pointed directly to a Gzip file

Am I forgetting something?

回答1:

If you download something with content type application/x-gzip, the url loading system will not decompress it for you. I think the data that you received is still gzip encoded.

You can use my NSData additions to deal with this. See http://github.com/st3fan/cocoa-utils/blob/master/src/NSDataGZipAdditions.m