gpt4 book ai didi

ios - 使用 swift 显示从 url 下载的图像的加载百分比

转载 作者:可可西里 更新时间:2023-10-31 23:55:19 24 4
gpt4 key购买 nike

所以我有一个像这样从 url 下载的图像

        let request = NSMutableURLRequest(URL: NSURL(string: "\(self.ip)")!)
request.HTTPMethod = "POST"
let postString = "userID=\(userID)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())

let task = session.dataTaskWithRequest(request) {
data, response, error in
.........
}

我的委托(delegate)函数看起来像

func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {

let uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
let progressPercent = Int(uploadProgress*100)
print(progressPercent)
}

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
let downloadProgress:Float = Float(downloadTask.countOfBytesReceived) / Float(downloadTask.countOfBytesExpectedToReceive)
print(downloadProgress)
}

上传进度对于不同的函数来说工作得很好,但是在下载图像时,不会调用第二个 URLSession 函数。我做错了什么?

最佳答案

URLSession 有 5 种类型的委托(delegate):URLSessionDelegateURLSessionTaskDelegateURLSessionDataDelegateURLSessionDownloadDelegateURLSessionStreamDelegate。您可以在 documentation 中阅读有关它们的信息.

你需要关心的是URLSessionDelegateURLSessionDownloadDelegate:

class ViewController: UIViewController, URLSessionDelegate, URLSessionDownloadDelegate {

@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var progressView: UIProgressView!

private let byteFormatter: ByteCountFormatter = {
let formatter = ByteCountFormatter()
formatter.allowedUnits = [.useKB, .useMB]
return formatter
}()

override func viewDidLoad() {
super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

@IBAction func downloadImage(sender : AnyObject) {
// A 10MB image from NASA
let url = URL(string: "https://photojournal.jpl.nasa.gov/jpeg/PIA08506.jpg")!

let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)

// Don't specify a completion handler here or the delegate won't be called
session.downloadTask(with: url).resume()
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let written = byteFormatter.string(fromByteCount: totalBytesWritten)
let expected = byteFormatter.string(fromByteCount: totalBytesExpectedToWrite)
print("Downloaded \(written) / \(expected)")

DispatchQueue.main.async {
self.progressView.progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
}
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
// The location is only temporary. You need to read it or copy it to your container before
// exiting this function. UIImage(contentsOfFile: ) seems to load the image lazily. NSData
// does it right away.
if let data = try? Data(contentsOf: location), let image = UIImage(data: data) {
DispatchQueue.main.async {
self.imageView.contentMode = .scaleAspectFit
self.imageView.clipsToBounds = true
self.imageView.image = image
}
} else {
fatalError("Cannot load the image")
}

}
}

关于ios - 使用 swift 显示从 url 下载的图像的加载百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38060567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com