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

时间:2017-03-11 23:28:10

标签: swift asynchronous foreach alamofire

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

我的代码是一个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栏在下载时疯狂,因为它会立即下载所有内容。我相信我已经建立了一个同步循环,但它可能仍然是异步的,因为它是循环的。

如何在此阻止异步下载?

1 个答案:

答案 0 :(得分:5)

使用信号量,因此一次只能下载一个信号量:

{'Text': u"What?...", 'Created At': datetime.datetime(2017, 3, 12, 2, 55, 6), 'Coordinates': {u'type': u'Point', u'coordinates': [-74.
1234567, 40.1234567]}}
{'Text': u'WHEN?...', 'Created A
t': datetime.datetime(2017, 3, 12, 2, 55, 8), 'Coordinates': None}
{'Text': u'Wooo...', 'Created At': datetime.datetime(2017, 3, 12, 2, 55, 9), 'Coordinates': None}
{'Text': u'Man...', 'Created At': datetime.datetime(2017, 3, 12, 2, 55, 9), 'Coordina
tes': None}
{'Text': u'The...', 'Created At': datetime.datetime(201
7, 3, 12, 2, 55, 10), 'Coordinates': None}