gpt4 book ai didi

ios - 快速从 dataTaskWithURL 获取进度

转载 作者:IT王子 更新时间:2023-10-29 05:19:58 26 4
gpt4 key购买 nike

有什么方法可以在下载数据时快速从 dataTaskWithURL 获取进度?

NSURLSession.sharedSession().dataTaskWithURL(...)

我需要在下载数据时显示进度条。

最佳答案

您可以简单地观察 URLSessionDataTask 对象的 progress 属性。

示例:

import UIKit

class SomeViewController: UIViewController {

private var observation: NSKeyValueObservation?

deinit {
observation?.invalidate()
}

override func viewDidLoad() {
super.viewDidLoad()

let url = URL(string: "https://source.unsplash.com/random/4000x4000")!
let task = URLSession.shared.dataTask(with: url)

observation = task.progress.observe(\.fractionCompleted) { progress, _ in
print("progress: ", progress.fractionCompleted)
}

task.resume()
}
}

Playground 示例:

import Foundation
import PlaygroundSupport

let page = PlaygroundPage.current
page.needsIndefiniteExecution = true

let url = URL(string: "https://source.unsplash.com/random/4000x4000")!
let task = URLSession.shared.dataTask(with: url) { _, _, _ in
page.finishExecution()
}

// Don't forget to invalidate the observation when you don't need it anymore.
let observation = task.progress.observe(\.fractionCompleted) { progress, _ in
print(progress.fractionCompleted)
}

task.resume()

关于ios - 快速从 dataTaskWithURL 获取进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30543806/

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