2

I received a string from a web service like this:

CAAAAB+LCAAAAAAABADtvQdgHEmWJSYvbcp7f0r1StfgdKEIgGATJNiQQBDswYjN5pLsHWlHIymrKoHKZVZlXWYWQMztnbz33nvvvffee++997o7nU4n99//P1xmZAFs9s5K2smeIYCqyB8/fnwfPyJOp/PqTf6u/X8A1v85+wgAAAA=

The source string was "EchoText" that compressed with Gzip then converted to Base64.

I have to decode Base64 string at first then Unzip that using Gzip.

How can I do in Swift (or Objective-C)?


Edit:

I found a good library for using Gzip: nicklockwood/Gzip

and it's my code:

    NSString* base64String = @"CAAAAB+LCAAAAAAABADtvQdgHEmWJSYvbcp7f0r1StfgdKEIgGATJNiQQBDswYjN5pLsHWlHIymrKoHKZVZlXWYWQMztnbz33nvvvffee++997o7nU4n99//P1xmZAFs9s5K2smeIYCqyB8/fnwfPyJOp/PqTf6u/X8A1v85+wgAAAA=";

NSData* compressedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];

NSData* unCompressedData = [compressedData gunzippedData];

NSString *result = [[NSString alloc] initWithData:unCompressedData encoding:NSUTF8StringEncoding];

but the result is nil.

  • What was used to do the gzip compression? It horribly "compressed" eight characters to a 127 byte gzip file! It should have compressed to 28 bytes, 18 of which are the gzip header and trailer. So the expansion should have only been taking 8 bytes to 10 bytes. – Mark Adler Nov 18 '14 at 18:28
  • Thanks for your comment but it's only a simple example, the main data i receive is bigger. –  Nov 20 '14 at 13:35

1 Answers1

2

This answer here covers Base64.

zlib is available directly as a shared library on Mac OS X and iOS. It can decompress gzip streams.

Note that the first four bytes of your example have to be stripped before you get to the gzip stream. They appear to contain the size of the uncompressed data in little-endian form. (They are 08 00 00 00 in your example.)

Community
  • 1
  • 1
Mark Adler
  • 101,978
  • 13
  • 118
  • 158
  • I know how to convert Base64 string to a NSData object but i don't know how to strip the first four bytes from NSData and i can't find any useful example of zlib in objective-c. sorry! i'm new in iOS programming. –  Nov 20 '14 at 13:41
  • I found a way to stripping the first four bytes and my problem solved. Thank's –  Nov 20 '14 at 14:53
  • 2
    @Ehsan Can you please provide your complete solution? – imike Feb 08 '16 at 11:32