简体   繁体   English

快速完成补给块

[英]Return in Completion Block Swift

I'm implementing the KolodaView available at: https://github.com/Yalantis/Koloda . 我执行KolodaView请访问: https://github.com/Yalantis/Koloda The viewForCardAt function returns a UIView , and my UIView will have an image which needs to be downloaded. viewForCardAt函数返回一个UIView ,我的UIView将具有需要下载的图像。 The problem is that the function itself expects a return type of UIView but I have no way of knowing when the completion block of the setupCard method is done executing, therefore I might end up returning an empty FlatCard instead of the FlatCard obtained in the completion block. 问题在于该函数本身期望返回UIView类型,但是我无法知道setupCard方法的完成块setupCard完成执行,因此我可能最终返回一个空FlatCard而不是在完成块中获得的FlatCard I tried adding return a to the completion block, but this isn't allowed. 我尝试将return a添加到完成块,但这是不允许的。 How can I change the code below to guarantee that a card is only returned once the completion block is executed. 如何更改下面的代码,以确保仅在完成补全块执行后才归还卡片。

func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {

    var a = FlatCard()
    if let listings = all_listings {
        if index < listings.count {
            setupCard(index: index, listings: listings, { (complete, card) in
                if (complete) {
                    a = card
                }
            })
            return a
        }
     }
    return a
}

func setupCard(index: Int, listings : [Listing], _ completionHandler: @escaping (_ complete: Bool, _ card : FlatCard) -> ()) -> (){

    let curr_card = FlatCard()

    if let main_photo_url = listings[index].pic1url {
        URLSession.shared.dataTask(with: main_photo_url, completionHandler: { (data, response, error) in

            if (error != nil) {
                print(error)
                return
            }

            DispatchQueue.main.async {
                curr_card.mainFlatImage = UIImage(data: data!)
            }
        })
        completionHandler(true,curr_card)
        return
    } else {
        completionHandler(true,curr_card)
        return
    }
}

You cannot return something before it is ready. 准备就绪之前,您无法退货。

Personally, I would update FlatCard so that it can download the image itself and update it's own view when done. 就个人而言,我将更新FlatCard,以便它可以下载图像本身并在完成后更新其自己的视图。

Something along the lines of 遵循以下原则

class FlatView: UIView {

    var imageURL: URL? {
        didSet {
            if let imageURL = newValue {
                 // download image, if success set the image on the imageView
            }
        }
    }
}

Then all that you need to do in your other function is... 那么您在其他功能中需要做的就是...

func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {

    var a = FlatCard()
    if let listings = all_listings {
        if index < listings.count {
            a.imageURL = listings[index].pic1url
        }
     }
    return a
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM