从网址解压缩SSZipArchive

时间:2017-05-17 09:40:56

标签: ios swift ssziparchive

我正在使用SSZipArchive从网址(http://www.colorado.edu/conflict/peace/download/peace.zip)解压缩文件。为此,我使用的功能是:

SSZipArchive.unzipFile(atPath: path, toDestination: documentsPath, progressHandler: {  
  1. 是否可以使用SSZipArchive从Url中提取文件?
  2. 是的,如何在 atPath 中传递网址?

1 个答案:

答案 0 :(得分:0)

如果不从网址下载文件,则无法直接解压缩 这就是我这样做的方式,

func downLoad() {
    let url : String = "http://www.colorado.edu/conflict/peace/download/peace.zip"
    var localPath: NSURL?
    Alamofire.download(.GET,url,
        destination: { (temporaryURL, response) in
            let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
            let pathComponent = response.suggestedFilename
            localPath = directoryURL.URLByAppendingPathComponent(pathComponent!)
            return localPath!
    })
        .response { (request, response, _, error) in
            SwiftEventBus.post("DownloadedSuccessfully", sender: localPath!)
    }  
}

下载内容后,将其解压缩到您想要的位置。

SwiftEventBus.onMainThread(self, name:"DownloadedSuccessfully")
    {
        result in

        let resultStatus = result.object as! NSURL

        guard let zipPath: String = resultStatus.path! as String else {
            return
        }
        guard let unZipPath = unzipPath() else {
            return
        }

        let success = SSZipArchive.unzipFileAtPath(zipPath, toDestination: unZipPath)
        print(unZipPath)
        if !success {
            return
        }
    }

我解压缩文件并将其存储在文档目录

func unzipPath() -> String? {
    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    let url = NSURL(fileURLWithPath: path)
    do {
        try NSFileManager.defaultManager().createDirectoryAtURL(url, withIntermediateDirectories: true, attributes: nil)
    } catch {
        return nil
    }
    if let path = url.path {
        return path
    }
    return nil
}

从那里您可以访问该文件的数据。在这里,我使用了第三方框架Alamofire和swiftEventBus。希望这对你有用。