gpt4 book ai didi

Swift - 阻止循环继续直到下载操作完成

转载 作者:行者123 更新时间:2023-11-28 09:43:02 24 4
gpt4 key购买 nike

我目前正在尝试根据用户对游戏的请求下载多个文件。我的目标是让它一次只下载一个文件并停止执行代码,直到该文件下载完成。

我的代码是一个 JSON 对象数组,每个对象都包含一个用于将它们下载到的路径(路径)和文件的 URL。我循环遍历数组并使用 AlamoFire 通过 .downloadProgress 闭包下载它们。

Alamofire.download(
json["url"].stringValue,
method: .get,
to: destination).downloadProgress(closure: { (Alamoprogress) in
info.stringValue = "Downloading: " + filename
progress.doubleValue = Alamoprogress.fractionCompleted * 100
}).response(completionHandler: { (DefaultDownloadResponse) in
})

为了确保它一次只下载一个文件,我设置了一个 DispatchQueue 并将 Alamofire 请求移到同步操作中:

for jsonObject in jsonArray{
queue.async {
print("Started downloading " + filename)
info.stringValue = "Downloading: " + filename
info.placeholderString = "Downloading: " + filename
info.isEnabled = true
info.isHidden = false
progress.isHidden = false
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = filepath
return (documentsURL, [.removePreviousFile])
}
Alamofire.download(
json["url"].stringValue,
method: .get,
to: destination).downloadProgress(closure: { (Alamoprogress) in
info.stringValue = "Downloading: " + filename
progress.doubleValue = Alamoprogress.fractionCompleted * 100
}).response(completionHandler: { (DefaultDownloadResponse) in
})
}
}

但是,调试日志将在下载文件时继续循环并将它们a同步下载。这会导致 info 框和 progress 栏在下载时变得异常,因为它是一次下载它们。我相信我已经设置了一个同步循环,但它可能仍然是异步的,因为它正在循环。

如何防止异步下载?

最佳答案

使用信号量,一次只有一个在下载:

let semaphore = DispatchSemaphore(value: 1)

for jsonObject in jsonArray {
queue.async {
semaphore.wait()

print("Started downloading " + filename)
info.stringValue = "Downloading: " + filename
info.placeholderString = "Downloading: " + filename
info.isEnabled = true
info.isHidden = false
progress.isHidden = false
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = filepath
return (documentsURL, [.removePreviousFile])
}
Alamofire.download( json["url"].stringValue, method: .get, to: destination)
.downloadProgress{ Alamoprogress in
info.stringValue = "Downloading: " + filename
progress.doubleValue = Alamoprogress.fractionCompleted * 100
}
.response { response in
semaphore.signal()
}
}
}

关于Swift - 阻止循环继续直到下载操作完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42741910/

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