Swift - 壓縮/解壓縮

  1. 下載SSZipArchive庫(kù)(新版本可能沒(méi)有createZipFileAtPath方法)
  2. 導(dǎo)入依賴動(dòng)態(tài)庫(kù)libz


壓縮目錄下的所有文件(SSZipArchive.createZipFileAtPath)

@IBAction func Compression(sender: UIButton) {
    let caches = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last
    let images = caches?.stringByAppendingString("/images")
    // 創(chuàng)建一個(gè)zip文件
    let zipFile = caches?.stringByAppendingString("/images.zip")
    // 把images目錄壓縮成zipFile文件
    let resule = SSZipArchive.createZipFileAtPath(zipFile, withContentsOfDirectory: images)
    if resule {
        /*********************把壓縮文件上傳到服務(wù)器*******************/
         // 非文件參數(shù)
        let params = [
            "username" : "李四"
        ]
        let mimeType = Tool.MIMEType(zipFile!)
        let data = NSData(contentsOfFile: zipFile!)
        Tool.upload(url, fileName: "images.zip", mimeType: mimeType, fileData: data!, params: params) { (response, data, error) -> () in
            // 得到返回的json
            let dict = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves)
            print(dict)
        }
        /*********************把壓縮文件上傳到服務(wù)器*******************/
    }
}

解壓縮從服務(wù)器下載的zip文件

@IBAction func Extract(sender: UIButton) {
    // 服務(wù)器上zip文件地址
    let url = NSURL(string: "http://localhost:8080/MJServer/resources/videos/videos.zip")
    // 發(fā)送請(qǐng)求,下載文件
    let task = NSURLSession.sharedSession().downloadTaskWithURL(url!) { (location, response, error) -> Void in
        // 拿到沙盒caches路徑
        let caches = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last
        // 解壓縮zip文件
        SSZipArchive.unzipFileAtPath(location?.path, toDestination: caches)
    }
    // 開(kāi)始下載
    task.resume()
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容