带有for循环和异步图像上传的完成处理程序

时间:2018-03-22 19:15:52

标签: swift firebase for-loop asynchronous completionhandler

我需要有一个完成处理程序或类似的东西,以确保每个图像都上传,下载网址存储在字典中。

func saveImages(images: [UIImage], completion: @escaping ([String : Any], String) -> Void) {

    let ref = FirDatabaseReference.courts.reference()
    let upload = ref.childByAutoId()
    let uploadID = upload.key

    // save images
    var urlDict = [String : Any]()
    DispatchQueue.main.async {
        for i in 0..<images.count {
            let saveID = "\(uploadID)_\(i)"
            let firImage = FIRImage(image: images[i])
            firImage.save(uploadID, imageUid: saveID, completion: { (url, error) in
                if error == nil {
                    urlDict["\(i)"] = url
                }
            })
        }
        completion(urlDict, uploadID)
    }
}

然而,使用空的urlDict立即调用完成,或者更好地说,没有添加任何内容。 我尝试了很多东西,但没有真正有用。我不知道在哪里放置Dispatch.main.asynch()调用,但我认为有必要。

1 个答案:

答案 0 :(得分:1)

完成是firImage.save调用的外部,所以它会在你得到回应之前执行

  // save images
var urlDict = [String : Any]()
DispatchQueue.main.async {
    for i in 0..<images.count {
        let saveID = "\(uploadID)_\(i)"
        let firImage = FIRImage(image: images[i])
        firImage.save(uploadID, imageUid: saveID, completion: { (url, error) in
            if error == nil {
                urlDict["\(i)"] = url
                completion(urlDict, uploadID)

            }
        })
    }

}

这个完成将被多次调用,直到完成数组计数等于你为for循环设置的images.count