Swift - 壓縮/解壓縮

  1. 下載SSZipArchive庫(新版本可能沒有createZipFileAtPath方法)
  2. 導入依賴動態庫libz


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

@IBAction func Compression(sender: UIButton) {
    let caches = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last
    let images = caches?.stringByAppendingString("/images")
    // 創建一個zip文件
    let zipFile = caches?.stringByAppendingString("/images.zip")
    // 把images目錄壓縮成zipFile文件
    let resule = SSZipArchive.createZipFileAtPath(zipFile, withContentsOfDirectory: images)
    if resule {
        /*********************把壓縮文件上傳到服務器*******************/
         // 非文件參數
        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)
        }
        /*********************把壓縮文件上傳到服務器*******************/
    }
}

解壓縮從服務器下載的zip文件

@IBAction func Extract(sender: UIButton) {
    // 服務器上zip文件地址
    let url = NSURL(string: "http://localhost:8080/MJServer/resources/videos/videos.zip")
    // 發送請求,下載文件
    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)
    }
    // 開始下載
    task.resume()
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容