Zip使用


Zip使用

========================

感觉官方写得挺明白的

do {
    let filePath = Bundle.main.url(forResource: "file", withExtension: "zip")!
    let unzipDirectory = try Zip.quickUnzipFile(filePath) // Unzip
    let zipFilePath = try Zip.quickZipFiles([filePath], fileName: "archive") // Zip
}
catch {
  print("Something went wrong")
}
do {
    let filePath = Bundle.main.url(forResource: "file", withExtension: "zip")!
    let documentsDirectory = FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)[0]
    try Zip.unzipFile(filePath, destination: documentsDirectory, overwrite: true, password: "password", progress: { (progress) -> () in
        print(progress)
    }) // Unzip

    let zipFilePath = documentsFolder.appendingPathComponent("archive.zip")
    try Zip.zipFiles([filePath], zipFilePath: zipFilePath, password: "password", progress: { (progress) -> () in
        print(progress)
    }) //Zip

}
catch {
  print("Something went wrong")
}
Zip.addCustomFileExtension("file-extension-here")

我是这样用的

func unzipModels(_ path: [String], modelUrl: String, directory: String) {
    for item in path {
        let fileManager = FileManager.default
        let urls: [URL] = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
        let documentURL = urls.first!
        let url = documentURL.appendingPathComponent(directory + item)
        let urlForTemp = documentURL.appendingPathComponent("Temp", isDirectory: true)
        let destinationURL = documentURL.appendingPathComponent(directory + "File", isDirectory: true)
            while true {
                if fileManager.fileExists(atPath: url.path) {
                    break
                } else {
                    Thread.sleep(forTimeInterval: 1)
                    continue
                }
            }
        do {
            try Zip.unzipFile(url, destination: urlForTemp, overwrite: true, password: nil, progress: { (progress) in
                if progress == 1 {
                    do {
                        if fileManager.fileExists(atPath: destinationURL.path ) {
                            try fileManager.removeItem(atPath: destinationURL.path)
                        }
                        try fileManager.moveItem(atPath: urlForTemp.path, toPath: destinationURL.path)
                        try fileManager.removeItem(atPath: url.path)
                    } catch {
                        log(error)
                    }
                }
            })
        } catch {
            log(error)
        }
    }
}
func downloadModelsAndUnzip(_ path: [String], modelUrl: String, directory: String) {
    DispatchQueue.global().async {
        downloadModelsWithoutDispatchQueue(path, modelUrl: modelUrl, directory: directory)
        unzipModels(path, modelUrl: modelUrl, directory: directory)
    }
}

文章作者: 张赛东
文章链接: https://zsd.name
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 张赛东 !
评论
  目录