Gzip Decompression for iOS clients

Source: Internet
Author: User

The service side uses gzip compression, can greatly reduce the volume of the transmission packet, speed up the client network requests, to save the user traffic. When the value of the "content-encoding" property of the Httpheader returned by the server is gzip, the data is automatically decompressed, but sometimes it is decompressed by some gateways when the client has not yet received the data, so gzip does not work. You can therefore contract other policies to prevent the gateway from decompressing, such as tagging gzip in another header attribute.

So, we need to extract the gzip data ourselves. Here's how: add Libbz2.1.0.dylib in the framework library; Add a method to NSData:

-(NSData *) gzipunpack

{

if ([self length] = = 0) return self;

unsigned full_length = [self length];

unsigned half_length = [self length]/2;

Nsmutabledata *decompressed = [Nsmutabledata datawithlength:full_length + half_length];

BOOL done = NO;

int status;

Z_stream STRM;

strm.next_in = (BYTEF *) [self bytes];

strm.avail_in = [self length];

strm.total_out = 0;

Strm.zalloc = Z_null;

Strm.zfree = Z_null;

if (InflateInit2 (&STRM, (15+32)) = Z_OK) return nil;

while (!done) {

if (strm.total_out >= [decompressed length])

[decompressed increaselengthby:half_length];

Strm.next_out = [decompressed mutablebytes] + strm.total_out;

Strm.avail_out = [decompressed length]-strm.total_out;

Inflate another chunk.

Status = Inflate (&STRM, Z_sync_flush);

if (status = = z_stream_end) done = YES;

else if (status! = Z_OK) break;

}

if (Inflateend (&STRM)! = Z_OK) return nil;

Set real length.

if (done) {

[decompressed setLength:strm.total_out];

return [NSData datawithdata:decompressed];

}

return nil;

}

and introduce the header file #import "Zlib.h"

The data will be obtained directly by calling the unpack method to complete the decompression.

If the compilation appears link error, go to target's settings, find "Other Linker Flags" This item, add-lz on it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.