Swift: unzipping file

半城伤御伤魂 提交于 2021-02-11 06:13:37

问题


I’m trying to get String from txt file inside the zip file using native libcompression library. Actually I use the code from

  • https://github.com/mw99/DataCompression/blob/master/Sources/DataCompression.swift.

At first, I was doing:

let zip = try? Data(contentsOf: "/.../test.zip")    
let tmp: Data? = zip?.unzip()
let txt: String? = String(data: tmp!, encoding: .utf8)

But how do I get the contents of zip file and how do I get data from certain txt file?


回答1:


ZIP Foundation supports accessing individual entries in ZIP archives.
You have to initialize an archive by passing a file URL to the Archive initializer.
Afterwards you can access a specific entry via subscripting:

let fileManager = FileManager()
let currentWorkingPath = fileManager.currentDirectoryPath
var archiveURL = URL(fileURLWithPath: currentWorkingPath)
archiveURL.appendPathComponent("test.zip")
guard let archive = Archive(url: archiveURL, accessMode: .read) else  {
    return
}
guard let entry = archive["file.txt"] else {
    return
}
var destinationURL = URL(fileURLWithPath: currentWorkingPath)
destinationURL.appendPathComponent("out.txt")
do {
    try archive.extract(entry, to: destinationURL)
} catch {
    print("Extracting entry from archive failed with error:\(error)")
}

You can also directly access the contents of entry by using the closure based API. This allows you to process the entry without writing it to the file system first:

try archive.extract(entry, consumer: { (data) in
    print(data.count)
})


来源:https://stackoverflow.com/questions/51064483/swift-unzipping-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!