如何解压缩包含一个文件的大型zip文件并使用swift以字节为单位获取进度?

时间:2015-05-14 07:57:26

标签: ios swift streaming archive unzip

我尝试解压缩只包含一个项目(超过100MB)的大型zip文件,并希望在解压缩过程中显示进度。

我找到了解决方案,根据解压缩的文件数量可以确定进度,但在我的情况下,我只有一个大文件。所以我猜它必须由解压缩的字节数决定?

实际上我正在使用SSZipArchive和以下代码,它可以正常工作:

    var myZipFile:NSString="/Users/user/Library/Developer/CoreSimulator/Devices/mydevice/ziptest/testzip.zip";
    var DestPath:NSString="/Users/user/Library/Developer/CoreSimulator/Devices/mydevice/ziptest/";


    let unZipped = SSZipArchive.unzipFileAtPath(myZipFile as! String, toDestination: DestPath as! String);

我找不到解决方案。

是否有人提供样品的提示,样品或链接?

更新 下面的代码看起来会按预期工作,但只有一个文件被解压缩时,处理程序只会被调用一次(在解压缩结束时):

func unzipFile(sZipFile: String, toDest: String){

        SSZipArchive.unzipFileAtPath(sZipFile, toDestination: toDest, progressHandler: {
            (entry, zipInfo, readByte, totalByte) -> Void in


            println("readByte : \(readByte)") // <- This will be only called once, at the end of unzipping. My 500MB Zipfile holds only one file. 
            println("totalByte : \(totalByte)")


            //Asynchrone task
            dispatch_async(dispatch_get_main_queue()) {
                println("readByte : \(readByte)")
                println("totalByte : \(totalByte)")

                //Change progress value

            }
            }, completionHandler: { (path, success, error) -> Void in
                if success {
                    //SUCCESSFUL!!
                } else {
                    println(error)
                }
        })

    }

更新2:

As&#34; Martin R&#34;在SSArchive中分析,这是不可能的。 有没有其他方法来解压缩文件并显示基于kbytes的进度?

更新3:

在解决方案解释后,我改变了SSZipArchive.m&#34; roop&#34;如下。可能其他人也可以使用它:

FILE *fp = fopen((const char*)[fullPath UTF8String], "wb");
                while (fp) {
                    int readBytes = unzReadCurrentFile(zip, buffer, 4096);

                    if (readBytes > 0) {
                        fwrite(buffer, readBytes, 1, fp );
                        totalbytesread=totalbytesread+4096;
                        // Added by me
                        if (progressHandler)
                        {
                            progressHandler(strPath, fileInfo, currentFileNumber, totalbytesread);
                        }
                        // End added by me

                    } else {
                        break;
                    }
                }

4 个答案:

答案 0 :(得分:2)

您可以尝试以下代码:

    SSZipArchive.unzipFileAtPath(filePath, toDestination: self.destinationPath, progressHandler: { 
(entry, zipInfo, readByte, totalByte) -> Void in
      //Create UIProgressView
      //Its an exemple, you can create it with the storyboard...
      var progressBar : UIProgressView?
      progressBar = UIProgressView(progressViewStyle: .Bar)
      progressBar?.center = view.center
      progressBar?.frame = self.view.center
      progressBar?.progress = 0.0
      progressBar?.trackTintColor = UIColor.lightGrayColor();
      progressBar?.tintColor = UIColor.redColor();
      self.view.addSubview(progressBar)

      //Asynchrone task                
      dispatch_async(dispatch_get_main_queue()) {
           println("readByte : \(readByte)")
           println("totalByte : \(totalByte)")                               

           //Change progress value
           progressBar?.setProgress(Float(readByte/totalByte), animated: true)
           //If progressView == 100% then hide it
           if readByte == totalByte {
               progressBar?.hidden = true
           }
       }
}, completionHandler: { (path, success, error) -> Void in
    if success {
        //SUCCESSFUL!!
    } else {
        println(error)
    }
})

我希望我能帮到你!

Ysee

答案 1 :(得分:1)

要实现您的目标,您必须修改SSZipArchive的内部代码。

SSZipArchive使用minizip提供压缩功能。您可以在此处查看minizip解压缩API:unzip.h

在SSZipArchive.m中,您可以从fileInfo variable获取解压缩文件的未压缩大小。

您可以看到正在阅读解压缩的内容here

 FILE *fp = fopen((const char*)[fullPath UTF8String], "wb");
 while (fp) {
     int readBytes = unzReadCurrentFile(zip, buffer, 4096);
     if (readBytes > 0) {
         fwrite(buffer, readBytes, 1, fp );
     } else {
         break;
     }
 }

您需要readBytes和未压缩的文件大小来计算单个文件的进度。您可以向SSZipArchive添加新委托,以将这些数据发送回调用代码。

答案 2 :(得分:0)

据我了解,最明显的答案是修改SSZipArchive的内部代码。但是我决定采用不同的方式并编写了此扩展名。理解起来相当简单,但是请不要犹豫,问任何问题。

此外,如果您认为我的解决方案有缺陷或知道如何改进它,我将很高兴听到它。

这是一个解决方案:

import Foundation
import SSZipArchive

typealias ZippingProgressClosure = (_ zipBytes: Int64, _ totalBytes: Int64) -> ()
private typealias ZipInfo = (contentSize: Int64, zipPath: String, progressHandler: ZippingProgressClosure)

extension SSZipArchive
{
    static func createZipFile(atPath destinationPath: String,
                              withContentsOfDirectory contentPath: String,
                              keepParentDirectory: Bool,
                              withPassword password: String? = nil,
                              byteProgressHandler: @escaping ZippingProgressClosure,
                              completionHandler: @escaping ClosureWithSuccess)
    {
        DispatchQueue.global(qos: .background).async {

            var timer: Timer? = nil
            DispatchQueue.main.async {

                //that's a custom function for folder's size calculation
                let contentSize = FileManager.default.sizeOfFolder(contentPath) 
                timer = Timer.scheduledTimer(timeInterval: 0.1,
                                             target: self,
                                             selector: #selector(progressUpdate(_:)),
                                             userInfo: ZipInfo(contentSize: contentSize,
                                                               zipPath: destinationPath,
                                                               progressHandler: byteProgressHandler),
                                             repeats: true)
            }

            let isSuccess = SSZipArchive.createZipFile(atPath: destinationPath,
                                                       withContentsOfDirectory: contentPath,
                                                       keepParentDirectory: keepParentDirectory,
                                                       withPassword: password,
                                                       andProgressHandler: nil)

            DispatchQueue.main.async {
                timer?.invalidate()
                timer = nil
                completionHandler(isSuccess)
            }
        }
    }

    @objc private static func progressUpdate(_ sender: Timer)
    {
        guard let info = sender.userInfo as? ZipInfo,
            FileManager.default.fileExists(atPath: info.zipPath),
            let zipBytesObj = try? FileManager.default.attributesOfItem(atPath: info.zipPath)[FileAttributeKey.size],
            let zipBytes = zipBytesObj as? Int64 else {
                return
        }

        info.progressHandler(zipBytes, info.contentSize)
    }
}

方法就这样使用:

SSZipArchive.createZipFile(atPath: destinationUrl.path,
                               withContentsOfDirectory: fileUrl.path,
                               keepParentDirectory: true,
                               byteProgressHandler: { (zipped, expected) in

                                //here's the progress code
    }) { (isSuccess) in
        //here's completion code
    }

优点:您不需要修改内部代码,内部代码会随着pods更新而被覆盖

缺点:如您所见,我正在以0.1秒的间隔更新文件大小信息。我不知道获取文件元数据是否会导致性能超载,而且我也找不到任何信息。

无论如何,我希望我能帮助别人:)

答案 3 :(得分:0)

SSZipArchive已有六年没有更新,您需要一个新的选择。

Zip:用于压缩和解压缩文件的Swift框架。

let filePath = Bundle.main.url(forResource: "file", withExtension: "zip")!
let documentsDirectory = FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)[0]
try Zip.unzipFile(filePath, destination: documentsDirectory, overwrite: true, password: "password", progress: { (progress) -> () in
    print(progress)
}) // Unzip

let zipFilePath = documentsFolder.appendingPathComponent("archive.zip")
try Zip.zipFiles([filePath], zipFilePath: zipFilePath, password: "password", progress: { (progress) -> () in
    print(progress)
}) //Zip