How to compress data in swift 3?

ぐ巨炮叔叔 提交于 2019-12-22 10:43:35

问题


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.


回答1:


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)



回答2:


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

let compressedData = fileData.compress(withAlgorithm: .LZFSE) as Data


来源:https://stackoverflow.com/questions/45657962/how-to-compress-data-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!