Swift-文件压缩和解压

项目中有时候需要文件下载解压,项目中选择了ZipArchive,实际使用也比较简单,直接调用解压和压缩方法即可.

压缩

<pre><code>`

@IBAction func zipAction(_ sender: UIButton) {
    let imageDataPath = Bundle.main.bundleURL.appendingPathComponent("FlyElephant").path
    
    zipPath = tempZipPath()
    
    let success = SSZipArchive.createZipFile(atPath: zipPath!, withContentsOfDirectory: imageDataPath)
    if success {
        print("压缩成功---\(zipPath!)")
    }
}`</code></pre>

解压

<pre><code>`

@IBAction func unZipAction(_ sender: UIButton) {
    guard let zipPath = self.zipPath else {
        return
    }
    
    guard let unzipPath = tempUnzipPath() else {
        return
    }
    
    let success = SSZipArchive.unzipFile(atPath: zipPath, toDestination: unzipPath)
    if !success {
        return
    }
    print("解压成功---\(unzipPath)")
    var items: [String]
    do {
        items = try FileManager.default.contentsOfDirectory(atPath: unzipPath)
    } catch {
        return
    }
    
    for (index, item) in items.enumerated() {
        print("\(index)--文件名称---\(item)")
    }
}`</code></pre>

压缩和解压路径:
<pre><code>`

func tempZipPath() -> String {
    var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
    path += "/\(UUID().uuidString).zip"
    return path
}

func tempUnzipPath() -> String? {
    var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
    path += "/\(UUID().uuidString)"
    let url = URL(fileURLWithPath: path)
    
    do {
        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
    } catch {
        return nil
    }
    
    
    return url.path
}`</code></pre>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,005评论 25 709
  • Ubuntu的发音 Ubuntu,源于非洲祖鲁人和科萨人的语言,发作 oo-boon-too 的音。了解发音是有意...
    萤火虫de梦阅读 100,035评论 9 468
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,450评论 4 61
  • 这剧看下来也是被虐得够够的了,终于在今天看完了结局。这个时候如果说有什么对结局的吐槽的话,只能说:实在是有些...
    EriChange_阅读 2,985评论 0 1
  • 语文不及格的我终于有勇气拿起手机记录成长的足迹了,不知道从幼儿园到高中的老师知道了会不会有些安慰(为什么没有大学呢...
    蝶梦初醒阅读 3,349评论 0 0

友情链接更多精彩内容