迅速:文件解压缩时显示UIActivityIndi​​catorView

时间:2018-08-01 08:59:36

标签: ios swift

我使用此代码下载文件,并在标签中显示下载进度。

我的代码:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MasterViewCell

    let cellFilePath = "\(indexPath.section)\(indexPath.row).zip"
    let indexOfTask = allDownloadTasks.index { (task:URLSessionDownloadTask) -> Bool in
        return task.currentRequest?.url?.lastPathComponent == cellFilePath
    }

    if indexOfTask == nil {

        //cell.label?.isHidden = true
    }
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 

    let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    let documentDirectoryPath:String = path[0]
    let fileManager = FileManager()
    let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/file.png"))

     if fileManager.fileExists(atPath: destinationURLForFile.path){
         animation()
     } else {

         let url = URL(string: "link")!
         let downloadTaskLocal = self.backgroundSession.downloadTask(with: url)
         self.allDownloadTasks.append(downloadTaskLocal) // Add a new task to the array
         downloadTaskLocal.resume()

         cell.label?.frame = CGRect(x: 70, y: 128, width: 82, height: 21)
         cell.label?.isHidden = false

     }
}

func urlSession(_ session: URLSession,
                    downloadTask: URLSessionDownloadTask,
                    didWriteData bytesWritten: Int64,
                    totalBytesWritten: Int64,
                    totalBytesExpectedToWrite: Int64){

        DispatchQueue.main.async(execute: {() -> Void in

            if let visibleIndexPath = self.collectionView?.indexPathsForVisibleItems {
                for visibleIndexPath in visibleIndexPath {
                    if (downloadTask.currentRequest?.url?.lastPathComponent == "\(visibleIndexPath.section)\(visibleIndexPath.row).zip") {

                        var myCell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: visibleIndexPath) as! MasterViewCell
                        myCell = self.collectionView?.cellForItem(at: visibleIndexPath) as! MasterViewCell

                        myCell.label.text = "\(Int(CGFloat(totalBytesWritten) / CGFloat(totalBytesExpectedToWrite) * 100.0))%"

                    if myCell.label?.text == "100%" {
                        myCell.label?.isHidden = true
                        myCell.activityIndicator?.isHidden = true
                        myCell.activityIndicator?.startAnimating()
                    }

                    }
                }
            }
        })
    }

我有以下代码来解压缩文件:

func urlSession(_ session: URLSession,
                downloadTask: URLSessionDownloadTask,
                didFinishDownloadingTo location: URL){

    let fileName = downloadTask.originalRequest?.url?.lastPathComponent
    let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    let documentDirectoryPath:String = path[0]
    let fileManager = FileManager()
    let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/\(String(describing: fileName!))"))

    do {
        try fileManager.moveItem(at: location, to: destinationURLForFile)
    }catch{
        print("error")
    }

    let indexOfComplatedTask = allDownloadTasks.index(of: downloadTask)
    if indexOfComplatedTask != nil {

        SSZipArchive.unzipFile(atPath: documentDirectoryPath.appendingFormat("/\(String(describing: fileName!))"), toDestination:documentDirectoryPath, delegate:self)

        do {
            try fileManager.removeItem(atPath: documentDirectoryPath.appendingFormat("/\(String(describing: fileName!))"))
        }
        catch let error as NSError {
            print("Ooops! Something went wrong: \(error)")
        }

    }
}

我想在文件解压缩时向我的activityIndicator显示开始动画,并在文件停止解压缩后停止动画并删除它。另外,我在情节提要中创建了label和activityIndi​​cator。

如何做到????

2 个答案:

答案 0 :(得分:0)

也许您可以切换到ZIP Foundation-它也具有简单的解压缩方法,并且支持进度跟踪。因此,您甚至可以显示某种进度指示器。

解压缩代码类似于您上面发布的代码:

let fileManager = FileManager()
let currentWorkingPath = fileManager.currentDirectoryPath
var sourceURL = URL(fileURLWithPath: currentWorkingPath)
sourceURL.appendPathComponent("archive.zip")
var destinationURL = URL(fileURLWithPath: currentWorkingPath)
destinationURL.appendPathComponent("directory")
do {
    try fileManager.createDirectory(at: destinationURL, withIntermediateDirectories: true, attributes: nil)
    try fileManager.unzipItem(at: sourceURL, to: destinationURL)
} catch {
    print("Extraction of ZIP archive failed with error:\(error)")
}

有关进度跟踪的一些详细信息可以在这里找到: https://github.com/weichsel/ZIPFoundation#progress-tracking-and-cancellation

答案 1 :(得分:0)

检查以下代码。

do {
        try fileManager.moveItem(at: location, to: destinationURLForFile)
    }catch{
        print("error")
    }

    let indexOfComplatedTask = allDownloadTasks.index(of: downloadTask)
    if indexOfComplatedTask != nil {
    **// Start animating your activityIndicator here.
    // Use unzipFile API having completion block callback
    // In the completion callback stop your activityIndicator**
        SSZipArchive.unzipFile(atPath: documentDirectoryPath.appendingFormat("/\(String(describing: fileName!))"), toDestination:documentDirectoryPath, delegate:self)

让我知道是否有疑问。