[英]Return in Completion Block Swift
我执行KolodaView请访问: https://github.com/Yalantis/Koloda 。 viewForCardAt
函数返回一个UIView
,我的UIView
将具有需要下载的图像。 问题在于该函数本身期望返回UIView
类型,但是我无法知道setupCard
方法的完成块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
}
}
准备就绪之前,您无法退货。
就个人而言,我将更新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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.