返回完成块Swift

问题描述 投票:0回答:1

我正在实施KolodaView:https://github.com/Yalantis/KolodaviewForCardAt函数返回UIView,我的UIView将有一个需要下载的图像。问题是函数本身需要UIView的返回类型,但我无法知道setupCard方法的完成块何时执行完毕,因此我可能最终返回一个空的FlatCard而不是在完成块中获得的FlatCard 。我尝试将return a添加到完成块,但这是不允许的。如何更改下面的代码以保证只有在执行完成块后才返回卡。

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
    }
}
ios swift nsurlsession completionhandler koloda
1个回答
1
投票

在准备好之前你不能退货。

就个人而言,我会更新FlatCard,以便它可以下载图像本身并在完成后更新它自己的视图。

有点像

class FlatView: UIView {

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

那么你在其他功能中需要做的就是......

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
}
© www.soinside.com 2019 - 2024. All rights reserved.