Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 756
Saeed Rahmatolahi Avatar asked Aug 13 '17 07:08

Saeed Rahmatolahi


People also ask

How do I compress a dataset?

One way to compress a data set is to use the COMPRESS=YES system option: options compress=yes; All subsequently created data sets will be stored in compressed form.

How do I compress a PDF in Swift?

Open the PDF file you need to shrink and choose File > Export. In the File window, make sure the Format is PDF, then choose Reduce File Size from the Quartz Filter drop-down.

Is it possible to compress data?

Data compression is a process in which the size of a file is reduced by re-encoding the file data to use fewer bits of storage than the original file. A fundamental component of data compression is that the original file can be transferred or stored, recreated, and then used later (with a process called decompression).


Video Answer


2 Answers

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)
like image 148
Juri Noga Avatar answered Sep 24 '22 14:09

Juri Noga


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

let compressedData = fileData.compress(withAlgorithm: .LZFSE) as Data
like image 26
Wil Shipley Avatar answered Sep 25 '22 14:09

Wil Shipley