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.
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.
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.
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).
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)
For reference, as of Swift 5.1 the way to do this is:
let compressedData = fileData.compress(withAlgorithm: .LZFSE) as Data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With