快速完成和循环问题

时间:2018-08-17 16:36:01

标签: swift download alamofire handler completion

尝试从三个网址之一下载PKG文件。逻辑基本上从每个下载URL中找到下载的延迟,然后将最终下载URL设置为具有最低延迟的主机。

DimName = "mm-" & format(DimScale,"0000")

这是通过循环遍历每个下载URL并用键作为url和值作为等待时间填充字典来完成的。当脚本继续从“最快的”下载URL下载时,它失败并显示nil。

我假设这是因为脚本在完成处理程序仍在运行时仍在继续运行,而字典中还没有任何内容,但是我将如何解决呢?

1 个答案:

答案 0 :(得分:1)

根据@vadian在Synchronous request using Alamofire的回答

...

let group = DispatchGroup()
var share_response = [String: Double]()
var package_sources: NSArray! = ["https://www.jss1.com/Share", "https://www.jss2.com/Share", "https://www.jss3.com/Share"]
let package_names: String = ["Dummy1.pkg", "Dummy2.pkg", "Dummy3.pkg"]
// Loop through the package sources and find the one with 
// the lowest latency.
for share_url in package_sources {
    group.enter()
    getPKG(pkgName: "Dummy.pkg", dpUrl: share_url, completion: {
        group.leave()
        dlObject in
        if dlObject.latency != nil {
            share_response[share_url] = dlObject.latency
        } else {
            debugPrint("nothing yet")
        }
        return dlObject
    })
}

group.notify(queue: DispatchQueue.main) {    
    let final_download_url = share_response.min { a, b in a.value < b.value }

    //  Here is where it breaks and responds with nil

    for package in package_names {
        let download_url = URL(string: final_download_url + package)
        Download commands here...
    }
}