用到的第三方框架:
Alamofire
SSZipArchive
下載方法代碼:
func downLoadFile(url: String, saveFileName: String, pathExtension: String) {
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
documentsURL.appendPathComponent(saveFileName + "." + pathExtension)
return (documentsURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(url, to: destination).response { response in
if response.error == nil {
guard let desUrl = response.destinationURL else {return}
var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
path += "/\(saveFileName)/"
let pathURL = URL(fileURLWithPath: path)
do {
try FileManager.default.createDirectory(at: pathURL, withIntermediateDirectories: true, attributes: nil)
DSLog("解壓路徑:\(pathURL.path)")
} catch let err {
DSLog(err.localizedDescription)
}
let urlStr = desUrl.absoluteString
DSLog("源文件路徑:\(urlStr)")
let done = SSZipArchive.unzipFile(atPath: urlStr.replacingOccurrences(of: "file://", with: ""), toDestination: path)//解壓,兩個(gè)參數(shù)一個(gè)是文件的路徑,一個(gè)是解壓后的位置
if done {
DSLog("解壓成功")
//清除壓縮包
}else{
DSLog("解壓失敗")
}
}
}
}
調(diào)用方法代碼:
downLoadFile(url: "下載鏈接", saveFileName: "自定義名稱", pathExtension: "后綴")