Home > other >  Swift ZIPFoundation extract string in memory is not working
Swift ZIPFoundation extract string in memory is not working

Time:07-02

Hi I am using ZipFoundation in Swift from https://github.com/weichsel/ZIPFoundation

My requirement is Unzip the file contents in memory and directly convert into String.

let archive = Archive(url: fileUrl, accessMode: .read, preferredEncoding: .utf8)
do{
   try archive?.extract(entry, consumer: {data in
      print(data.count)
    })
  }catch{}

The archive object is always null its not reading zip file. Also What is the entry object to pass to extract method?

Any help will be appreciated.

CodePudding user response:

ZIP Foundation archives support subscripting. This allows you to obtain an Entry by subscripting into an Archive via archive["path/to/file.txt"].

To get access to the contents of the obtained file, you use the closure-based version of extract as follows:

guard let archiveURL = Bundle.main.url(forResource: "archive", withExtension: "zip"),
      let archive = Archive(url: archiveURL, accessMode: .read),
      let entry = archive["test/data.random"]
else { return }

_ = try? archive.extract(entry) { data in
    print(data.count)
}
  • Related