Search code examples
iosswiftzipfoundation

Swift ZIPFoundation extract string in memory is not working


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?


Solution

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