Swift51.com
Swift 头像
Swift  2017-03-24 21:59

Swift 压缩和解压文件的框架 Zip

回复:0  查看:7965  感兴趣:82  赞:0  

Zip是一个用于压缩和解压文件的Swift框架。

快速上手

通过quickUnzipFile函数和quickZipFiles函数可以很方便的解压缩文件。两者都是用NSURLs类型的路径为参数,发生错误将抛出异常,成功则返回NSURL类型。

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")
}

高级用法

Zip提供了相关函数,可以自定义目标路径、设置密码、获取进度。这些方法出错时会抛出异常,成功时没有返回值。

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")
}


相关开源代码