这些是需要发生的方法和过程:
- 从 Parse 下载图像
- 下载关联数据(与图像匹配)
- 在 map 上绘制这些数据
这是我从 View 中加载的代码:
override func viewDidLoad() {
imageDownload { () -> () in
print("5-----inside closure")
self.queryParseandSave(callback: self.plotImages)
}
}
图片下载功能:
func imageDownload(completed: @escaping FinishedDownload){
print("1-----Started Image download")
// Query for places
let query = PFQuery(className:"ViewFinderObjects")
query.whereKey("ImageVerified", equalTo: true)
query.whereKey("coordinates", nearGeoPoint:myGeoPoint)
query.limit = 10
query.findObjectsInBackground { (objects, error) -> Void in
if (error == nil) {
for object in objects! {
print("2-----inside object for block")
let imageFromParse = object["image"] as! PFFile
imageFromParse.getDataInBackground(block: {(imageData, error) -> Void in
print("Searching for Image")
if error == nil {
let obsImage:UIImage = UIImage(data: imageData!)!
self.imageToShow = obsImage
self.closestImage.append(self.imageToShow!)
print("There are \(self.closestImage.count) images in the image array")
}
})
print("3-----Completed object loop")
}
}
print("4-----Calling completed statement")
completed()
}
}
然后调用另一个函数queryParseandSave(callback: self.plotImages)
使用 self.plotImages 在 map 上绘制图像。
我有 1 个大问题:
self.plotImahes
始终在图像下载完成之前调用
我研究了 async_dispatch 但不知道这是否是正确的做法。
最佳答案
我不熟悉 query.findObjectsInBackground
和 imageFromParse.getDataInBackground
方法的实现,但它们的命名意味着它们都是异步发生的。另外,从上面提供的内容来看,前者检索对象数据,而后者则下载实际的图像数据。如果确实如此,那么看起来您是在第一个异步方法的主体内调用完成处理程序,而不是等待第二个方法(似乎是实际的图像下载) .
关于如何解决此问题的一些想法:
- 您可以将完成处理程序移动到
imageFromParse.getDataInBackground
block 中,但只有当您愿意在每个图像下载完成后多次调用完成 block 时,这才有意义。 - 您可以创建自己的调度或操作队列并等待所有任务完成,然后调用完成处理程序。
- 您可以设置一个观察者或通知模式,以便在适当的时间调用您的完成处理程序。
有很多不同的方法可以解决这个问题,但要记住的关键是,听起来您想要在所有异步操作完成后调用完成处理程序。现在,您在检索对象后调用它,但当调用完成处理程序时,所有图像仍在后台下载。
关于ios - 完成处理程序?异步调度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41090770/