【发布时间】:2020-05-08 23:51:35
【问题描述】:
我正在尝试使用 Swift 包中的 URLSession 下载文件。这是我的代码:
public class Downloader: NSObject, URLSessionDownloadDelegate {
private lazy var session = URLSession(configuration: .default,
delegate: self,
delegateQueue: nil)
var semaphore: DispatchSemaphore?
public func download(fileAt url: URL) {
semaphore = DispatchSemaphore(value: 1)
session.downloadTask(with: url).resume()
semaphore!.wait()
}
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
print(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
}
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
print(location)
semaphore?.signal()
}
}
问题是当我尝试使用它时,应用程序立即存在而无需等待。我知道如何使用闭包回调设置信号量,但这种方法不起作用。我需要获取进度更新,所以我不能关闭方法。
如果有人可以提供帮助,那就太好了。
【问题讨论】:
标签: swift networking semaphore urlsession