Search code examples
iosswiftstringgzipnsdata

swift gzip data to string issue


I use gzip library to convert data to gzip data

If I want to get string from data I do String(data: data, encoding: .utf8) . But if I do the same for gzip data I get nil string, because as far as I understand it's impossible to convert gzip data to string with .utf8 encoding.

I need that because I want to compare data with a server developer (because he sometimes he says that my data is incorrect format, but sometimes it's ok, and that's strange because I use the same library, and I have thoughts that may be the problem is on server side).

Is there any way to convert gzip data to any string to compare it then later?


Solution

  • If this is just for debug purpose, then I think the quickest way is:

    let myGZipNSData = myGZipData as! NSData //I wrote a "!" just for the sample)
    print("myGZipNSData: \(myGZipNSData)")
    

    It should output:

    myGZipNSData: <5b226d79 41727261 7956616c 75653022 2c226d79 41727261 7956616c 75653122 5d>
    

    This relies on -description method of NSData which print "<hexValue>". Do not rely on it on release version, almost never rely on -description (yes, Apple could change the behavior of -description in next release. It happened on a different class).

    Other way (safer) to get almost the same result, you can check this question: How to convert Data to hex string in swift which you get you the same result (almost, less space, and no </>) as the previous one.

    Other way: Base 64 Use base64EncodedString() method of Data:

    let base64Str = myGZipData?.base64EncodedString()
    print("base64Str: \(base64Str!)")
    

    Output:

    base64Str: WyJteUFycmF5VmFsdWUwIiwibXlBcnJheVZhbHVlMSJd
    

    Now, there should be other way: Have a array representation with Int values (between 0/255 instead of hex), but it seems to be for debug purpose so check if you can "reproduce the current solutions" (working/fast implementation) I gave you, and check with the server developer what he/she can do on his/her side too to compare.

    Note: For the purpose of this sample, myGZipData is constructed this way:

    let array = ["myArrayValue0", "myArrayValue1"]
    
    let myGZipData = try? JSONSerialization.data(withJSONObject: array, options:[])
    

    It's not really a GZipData, but the goal was to quickly have a Data object "big enough".