ios gzip 解压实现

来源:互联网 发布:花千骨进阶数据大全 编辑:程序博客网 时间:2024/04/28 05:00


1.  加入头文件

#import "zlib.h"

 

2. 加入库 : libz.1.1.3.dylib 到xcode当中。


3. 加入函数:

-(NSData *)uncompressZippedData:(NSData *)compressedData

{

    if ([compressedDatalength] == 0)

        return compressedData;

    

    unsigned full_length = [compressedDatalength];

    

    unsigned half_length = [compressedDatalength] / 2;

    NSMutableData *decompressed = [NSMutableDatadataWithLength: full_length + half_length];

    BOOL done =NO;

    int status;

    z_stream strm;

    strm.next_in = (Bytef *)[compressedDatabytes];

    strm.avail_in = [compressedDatalength];

    strm.total_out =0;

    strm.zalloc =Z_NULL;

    strm.zfree =Z_NULL;

    if (inflateInit2(&strm, (15+32)) != Z_OK)

        returnnil;

    

    while (!done)

    {

        // Make sure we have enough room and reset the lengths.

        if (strm.total_out >= [decompressedlength]) {

            [decompressed increaseLengthBy: half_length];

        }

        // chadeltu 加了(Bytef *)

        strm.next_out = (Bytef *)[decompressedmutableBytes] + strm.total_out;

        strm.avail_out = [decompressedlength] - strm.total_out;

        // Inflate another chunk.

        status = inflate (&strm,Z_SYNC_FLUSH);

        if (status ==Z_STREAM_END) {

            done = YES;

        } elseif (status != Z_OK) {

            break;

        }

        

    }

    

    if (inflateEnd (&strm) !=Z_OK)

        returnnil;

    

    // Set real length.

    if (done) {

        [decompressed setLength: strm.total_out];

        return [NSDatadataWithData: decompressed];

    } else {

        returnnil;

    }

}


0 0
原创粉丝点击