- 下載SSZipArchive庫(新版本可能沒有createZipFileAtPath方法)
-
導(dǎo)入依賴動態(tài)庫libz
壓縮目錄下的所有文件(SSZipArchive.createZipFileAtPath)
@IBAction func Compression(sender: UIButton) {
let caches = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last
let images = caches?.stringByAppendingString("/images")
// 創(chuàng)建一個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ā)送請求,下載文件
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()
}