How to get the download progress in bytes using Alamofire 4?

守給你的承諾、 提交于 2019-12-06 07:49:36

问题


I'm currently working on an iOS project which requires me to download 10 different files at once. I know the file size and the size of all the files combined but I'm struggling to find a way to calculate the progress across all download tasks.

progress.totalUnitCount = object.size // The size of all the files combined
    for file in files {
        let destination: DownloadRequest.DownloadFileDestination = { _, _ in
            let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory,
                                                           FileManager.SearchPathDomainMask.userDomainMask, true)
            let documentDirectoryPath: String = path[0]
            let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath)
            return (destinationURLForFile, [.removePreviousFile, .createIntermediateDirectories])
        }

        Alamofire.download(file.urlOnServer, to: destination)
            .downloadProgress(queue: .main, closure: { progress in

            })
            .response { response in
                if let error = response.error {
                    print(error)
                }
        }
    }

Most of this code is just for context.

I discovered, that up to Alamofire 3 there was this call:

 .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
    print("Bytes: \(bytesRead), Total Bytes: \(totalBytesRead), Total Bytes Expected: \(totalBytesExpectedToRead)")
}

This is not present anymore and I'm wondering how I can get the same functionality.

Thank you in advance!


回答1:


In Alamofire 4 the Progress APIs changed. All changes are explained in the Alamofire 4.0 Migration Guide.

To sum up the most important changes, that affect your use case:

// Alamofire 3
Alamofire.request(.GET, urlString, parameters: parameters, encoding: .JSON)
.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
    print("Bytes: \(bytesRead), Total Bytes: \(totalBytesRead), Total Bytes Expected: \(totalBytesExpectedToRead)")
}

can be achieved with

// Alamofire 4
Alamofire.request(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default)
.downloadProgress { progress in
    print("Progress: \(progress.fractionCompleted)")
}

The returned progress object is of the Progress type of Apple's Foundation framework, so you can access the fractionCompleted property.

Detailed explanation of the changes can be found in the Request Subclasses section in the Alamofire 4.0 Migration guide. The pull request 1455 in the Alamofire GitHub repo introduces the new Progress APIs and might be of help as well.



来源:https://stackoverflow.com/questions/42727395/how-to-get-the-download-progress-in-bytes-using-alamofire-4

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