线程完成处理程序 Swift

Threading CompletionHandler Swift

我尝试从解析服务器获取数据。因此它需要 2 个后台线程。但我不知道它设法以正确的方式等待完成。所以我将其拆分为以下代码:

 func load(loadCompletion: @escaping () -> ()) {
    let delegate = object as! AppDelegate
    parseQuery.findObjectsInBackground { (result: [PFObject]?, error: Error?) in
        self.getAllData(result: result, delegate: delegate, error: error) {
            loadCompletion()
        }
    }
}

func getAllData(result: [PFObject]?, delegate: AppDelegate, error: Error?, allDataCompletion: @escaping () -> ()) {
    if error == nil && result != nil {
        for obj in result! {
            let date: Date = obj["Date"] as! Date
            let coordinates: PFGeoPoint = obj["Coordinates"] as! PFGeoPoint
            let imageFile: PFFileObject = obj["Image"] as! PFFileObject
            let lat: CLLocationDegrees = coordinates.latitude
            let long: CLLocationDegrees = coordinates.longitude
            let cllCoordinates = CLLocationCoordinate2D(latitude: lat, longitude: long)
            self.getImageData(imageFile: imageFile) { (image) in
                let poo = Poo(coordinates: cllCoordinates, dateTime: date, image: image)
                delegate.poos.append(poo)
            }
        }
        allDataCompletion()
    }
}

func getImageData(imageFile: PFFileObject, imageDataCompletion: @escaping (UIImage?) -> () ) {
    var image: UIImage? = nil
    imageFile.getDataInBackground { (data, error) in
        if error == nil && data != nil {
            image = UIImage(data: data!)
        }
        imageDataCompletion(image)
    }
}

所以,我想在委托中设置数组,但不幸的是,在填充数组之前调用了 loadCompletion()。请帮助我以正确的顺序获取此 运行。谢谢!

一个简单的解决方案是修改您的 getAllData 函数并在获取最后一个对象的图像数据后调用 allDataCompletion

func getAllData(result: [PFObject]?, delegate: AppDelegate, error: Error?, allDataCompletion: @escaping () -> ()) {
    if error == nil && result != nil {
        for (idx, obj) in result!.enumerated() {
            let date: Date = obj["Date"] as! Date
            let coordinates: PFGeoPoint = obj["Coordinates"] as! PFGeoPoint
            let imageFile: PFFileObject = obj["Image"] as! PFFileObject
            let lat: CLLocationDegrees = coordinates.latitude
            let long: CLLocationDegrees = coordinates.longitude
            let cllCoordinates = CLLocationCoordinate2D(latitude: lat, longitude: long)
            self.getImageData(imageFile: imageFile) { (image) in
                let poo = Poo(coordinates: cllCoordinates, dateTime: date, image: image)
                delegate.poos.append(poo)
                if idx == result!.endIndex-1{
                    allDataCompletion()
                }
            }
        }

    }
}

或使用DispatchGroup / Synchronizing Async Code