5

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.

Arnaud
  • 7,259
  • 10
  • 50
  • 71
Saeed Rahmatolahi
  • 1,317
  • 2
  • 27
  • 60

2 Answers2

9

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)
Juri Noga
  • 4,363
  • 7
  • 38
  • 51
5

For reference, as of Swift 5.1 the way to do this is:

let compressedData = fileData.compress(withAlgorithm: .LZFSE) as Data
Wil Shipley
  • 9,343
  • 35
  • 59