Unzipping files with SSZipArchive - Swift

限于喜欢 提交于 2019-12-21 20:42:56

问题


I'm trying to unzip a file using the SSZipArchive framework.

let unzipper = SSZipArchive.unzipFileAtPath(String(document), toDestination: String(documentsUrl))

This is what I'm trying at the moment to unzip the file, and here is the path of the file:

unzipFileAtPath - Document at path: file:///private/var/mobile/Containers/Data/Application/94ADDB12-78A2-4798-856D-0626C41B7AC2/Documents/tSOUTrIayb.zip false

And I am trying to unzip it to this path:

NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!

Unfortunately it doesn't seem to be working, each time there is nothing new being saved into the documents directory which I am printing out. I also print the 'unzipper' variable which just prints false, whatever that means.

I can't find any documentation for the framework so I'm not entirely sure how to get this working


回答1:


Assume that you have implement all things, then also providing solution in few steps

  1. Drag SSZipArchive folder from the demo which you can download from here.

  2. Write #import "SSZipArchive.h” in yourProjectname-Bridging-Header.h if you already have. Otherwise create new header file named as mention above.

  3. If you want to use delegate methods set delegate to class

    class YourViewController: UIViewController, SSZipArchiveDelegate {.......
    
  4. For creating zip form folder I have added sample folder to project (Main bundle)

  5. First create folder in document directory where you want to save your zip file

    var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentsDir = paths[0]
    let zipPath =  documentsDir.stringByAppendingString("/MyZipFiles") // My folder name in document directory
    
    let fileManager = NSFileManager.defaultManager()
    
    let success = fileManager.fileExistsAtPath(zipPath) as Bool
    
    if success == false {
    
        do {
    
            try! fileManager.createDirectoryAtPath(zipPath, withIntermediateDirectories: true, attributes: nil)
        }
    }
    
  6. Now create zip file

    var inputPath = NSBundle.mainBundle().resourcePath
    inputPath = inputPath!.stringByAppendingString("/Sample") // My folder which already put into project
    
    let archivePath = zipPath.stringByAppendingString(“/Demo.zip") // Sample folder is going to zip with name Demo.zip
    SSZipArchive.createZipFileAtPath(archivePath, withContentsOfDirectory:inputPath)
    
  7. For unzipping file create folder in document directory (Where you want to save)

    let destPath = zipPath.stringByAppendingString("/Hello")
    let fileManager = NSFileManager.defaultManager()
    
    let success = fileManager.fileExistsAtPath(destPath) as Bool
    
    if success == false {
    
        do {
    
            try! fileManager.createDirectoryAtPath(destPath, withIntermediateDirectories: true, attributes: nil)
        }
    }
    
  8. Unzip folder

    SSZipArchive.unzipFileAtPath(archivePath, toDestination:destPath, delegate:self)
    
  9. Print your path, and you can check there your file will be saved

    print(zipPath)
    



回答2:


TLDR; check that your source and destination paths don't begin with the file:// prefix.

More Detail...

I had the same issue, SSZipArchive would run, the success variable would print out false, no delegates were called and no debug messages printed from SSZipArchive.

I was running it like this:

let sourcePath = sourceURL.absoluteString
let destPath = destURL.absoluteString

print("Source: \(sourcePath)")
print("Dest: \(destPath)")

let success = SSZipArchive.unzipFile(atPath: sourcePath, toDestination: destPath, delegate: self)
print("ZipArchive - Success: \(success)")

and my log statements were printing out

Source: file:///var/containers/Bundle/Application/longAppIDHere/testApp.app/Bundle1.zip
Dest: file:///var/mobile/Containers/Data/Application/longAppIDHere/Library/Application Support/testFolder/
ZipArchive - Success: false

I changed my path constructors to:

let sourcePath = sourceURL.relativePath
let destPath = destURL.relativePath

and now SSZipArchive works fine.




回答3:


I hope this helps someone. AEXML or SwiftyXMLParser, SSZipArchive

 //путь к файлу // path to file
    guard let bookPath = Bundle.main.path(forResource: "FileName", ofType: "epub") else {  return }
    //путь к хранилищу телефона // path to storage 
    let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
    let fileManager = FileManager.default
    let bookName = bookPath.lastPathComponent // название файла // name of file
    let bookBasePath = paths.appendingPathComponent(bookName) // ссылка к хранилищу телефона // path to Directory 

    do {
        if !fileManager.fileExists(atPath: bookBasePath) {
            SSZipArchive.createZipFile(atPath: bookPath, withContentsOfDirectory:bookBasePath) // создание архива // create zip
            SSZipArchive.unzipFile(atPath: bookPath, toDestination: bookBasePath, delegate: self) // распаковка архива // unzip 
            try FileManager.default.createDirectory(atPath: bookBasePath, withIntermediateDirectories: true, attributes: nil) // создание директории с архивом // create Directory
        }

        if fileManager.fileExists(atPath: bookBasePath){
            // get xml
            let containerPath = "META-INF/container.xml"
            let containerData = try Data(contentsOf: URL(fileURLWithPath: bookBasePath).appendingPathComponent(containerPath), options: .alwaysMapped) // получение xml файла из директории
            print(containerData)
           // parse xml ...
        } else {
            print("file no exists")
        }
    } catch {
        print(error)
    }


来源:https://stackoverflow.com/questions/33734588/unzipping-files-with-ssziparchive-swift

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