Search code examples
iosswift3base64compressionnsdata

How to compress data in swift 3?


I have some files in file manager in Swift 3. I want to upload them, but when I will convert them into base 64, their size will be huge! so I want to compress the data before converting it into base 64.

Here is my code for converting:

for i in 0...(rows?.count)! - 1 {

   let filePath = filesurl[fileManagerViewController.selectedFileIndex[i]]
        do {
            let fileData = try Data.init(contentsOf: filePath)

            let fileStream:String = fileData.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))

            fileManagerViewController.upupload.append(fileStream)


        } catch {
            print(error.localizedDescription)
        }


        }

I used

let compressedData = fileData(UF_COMPRESSED)

But that didn't work for me, so please help me compressing files before converting them into base 64 for uploading.


Solution

  • Here's libcompression wrapper written in Swift 3. https://github.com/mw99/SwiftDataCompression

    Swift libcompression wrapper as an extension for the Data type (ZLIB, LZFSE, LZMA, LZ4, deflate, RFC-1950, RFC-1951)

    So you can compress your data like that:

    let fileData = try Data.init(contentsOf: filePath)
    let compressedData = fileData.compress(withAlgorithm: .LZFSE)