Compress/Decompress NSString in objective-c (iphone) using GZIP or deflate

前端 未结 4 1601
遇见更好的自我
遇见更好的自我 2020-12-01 22:11

I have a web-service running on Windows Azure which returns JSON that I consume in my iPhone app.

Unfortunately, Windows Azure doesn\'t seem to support the compressi

4条回答
  •  粉色の甜心
    2020-12-01 22:39

    I needed to compress data on the iPhone using Objective-c and decompress on PHP. Here is what I used in XCode 11.5 and iOS 12.4:

    iOS Objective-c Compression Decompression Test Include libcompression.tbd in the Build Phases -> Link Binary With Library. Then include the header.

    #include "compression.h"
    
    
    NSLog(@"START META DATA COMPRESSION");
    NSString *testString = @"THIS IS A COMPRESSION TESTTHIS IS A COMPRESSION TESTTHIS IS A COMPRESSION TESTTHIS IS A COMPRESSION TESTTHIS IS A COMPRESSION TESTTHIS IS A COMPRESSION TEST";
    NSData *theData = [testString dataUsingEncoding:NSUTF8StringEncoding];
    size_t src_size = theData.length;
    uint8_t *src_buffer = (uint8_t*)[theData bytes];
    size_t dst_size = src_size+4096;
    uint8_t *dst_buffer = (uint8_t*)malloc(dst_size);
    dst_size = compression_encode_buffer(dst_buffer, dst_size, src_buffer, src_size, NULL, COMPRESSION_ZLIB);
    NSLog(@"originalsize:%zu compressed:%zu", src_size, dst_size);
    NSData *dataData = [NSData dataWithBytes:dst_buffer length:sizeof(dst_buffer)];
    NSString *compressedDataBase64String = [dataData base64EncodedStringWithOptions:0];    
    
    NSLog(@"Compressed Data %@", compressedDataBase64String);
    
    NSLog(@"START META DATA DECOMPRESSION");
    src_size = compression_decode_buffer(src_buffer, src_size, dst_buffer, dst_size, NULL, COMPRESSION_ZLIB);
    NSData *decompressed = [[NSData alloc] initWithBytes:src_buffer length:src_size];
    NSString *decTestString;
    decTestString = [[NSString alloc] initWithData:decompressed encoding:NSASCIIStringEncoding];
    
    NSLog(@"DECOMPRESSED DATA %@", decTestString);
    
    free(dst_buffer);
    

    On the PHP side I used the following function to decompress the data:

    function decompressString($compressed_string) {
    
        //NEED RAW GZINFLATE FOR COMPATIBILITY WITH IOS COMPRESSION_ZLIB WITH IETF RFC 1951
        $full_string = gzinflate($compressed_string);
        return $full_string;
    
    }  
    

提交回复
热议问题