ios - 完成处理程序?异步调度?

标签 ios swift asynchronous parse-platform closures

这些是需要发生的方法和过程:

  1. 从 Parse 下载图像
  2. 下载关联数据(与图像匹配)
  3. 在 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.findObjectsInBackgroundimageFromParse.getDataInBackground 方法的实现,但它们的命名意味着它们都是异步发生的。另外,从上面提供的内容来看,前者检索对象数据,而后者则下载实际的图像数据。如果确实如此,那么看起来您是在第一个异步方法的主体内调用完成处理程序,而不是等待第二个方法(似乎是实际的图像下载) .

关于如何解决此问题的一些想法:

  1. 您可以将完成处理程序移动到 imageFromParse.getDataInBackground block 中,但只有当您愿意在每个图像下载完成后多次调用完成 block 时,这才有意义。
  2. 您可以创建自己的调度或操作队列并等待所有任务完成,然后调用完成处理程序。
  3. 您可以设置一个观察者或通知模式,以便在适当的时间调用您的完成处理程序。

有很多不同的方法可以解决这个问题,但要记住的关键是,听起来您想要在所有异步操作完成后调用完成处理程序。现在,您在检索对象后调用它,但当调用完成处理程序时,所有图像仍在后台下载。

关于ios - 完成处理程序?异步调度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41090770/

相关文章:

javascript - 重写这个弗兰肯斯坦 promise 链

ios - 在 Swift xCode 中将 UI 导航栏设置为半透明

ios - 如何制作双线边框的UIButton?

javascript - axios 并发请求数 : any way to get the results from the successful requests even if some have failed?

javascript - 我的图像在 Chrome 和 Firefox 中显示,但在 Safari 或 iPhone 中不显示

ios - 如何在 Swift 中故意创建格式错误的 URL

ios - cordova ios 项目中 config.xml 中 <edit-config 的父标记是什么?

ios - PFQueryTableView 在新数据更新时自动刷新或使用 Parse 每分钟刷新一次

ios - Swift 中的 Objective C Setter 覆盖

javascript - 在回调中更新数组