【问题标题】:Wait for URLSession to finish in a Swift package等待 URLSession 在 Swift 包中完成
【发布时间】: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


    【解决方案1】:

    这可以通过添加 semaphore 作为 self 的属性来完成。应该在didCompleteWithErrordidFinishDownloadingTo 中发出信号。

    【讨论】:

      猜你喜欢
      • 2016-06-23
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 2015-04-11
      • 1970-01-01
      相关资源
      最近更新 更多