Alamofire下载文件,并解压

用到的第三方框架:
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)//解压,两个参数一个是文件的路径,一个是解压后的位置
                if done {
                    DSLog("解压成功")
                    //清除压缩包
                }else{
                    DSLog("解压失败")
                }
            }
        }
    }

调用方法代码:

downLoadFile(url: "下载链接", saveFileName: "自定义名称", pathExtension: "后缀")

你可能感兴趣的:(Alamofire下载文件,并解压)