How can I add records fetched asynchronously from json to the array only when all records are fetched in Swift?

匆匆过客 提交于 2019-12-11 11:49:42

问题


I'm working on a market cluster for apple maps (here is the plugin https://github.com/ribl/FBAnnotationClusteringSwift ) and I want to display all records on my map at once - for that I need to download all the records from remote webservice, add it to json (I've already done that) and then add all fetched points to an array.

My code looks like this:

let clusteringManager = FBClusteringManager()
var array:[FBAnnotation] = []

func loadInitialData() {
    RestApiManager.sharedInstance.getRequests { json in
        if let jsonData = json.array {
           for requestJSON in jsonData {
               dispatch_async(dispatch_get_main_queue(),{
               if let request = SingleRequest.fromJSON(requestJSON){

                let pin = FBAnnotation()
                pin.coordinate = CLLocationCoordinate2D(latitude: request.latitude, longitude: request.longitude)
                self.array.append(pin)

                }
                })
             }
          }
     }
}

as you can see I'm appending all pins to the array and at some point I need to use this array here:

self.clusteringManager.addAnnotations(array)

I thought I could just write the line above at the very end of my method loadInitialData, but then the array is still empty. How should I change my code so that it invokes the addAnnotations method when the array is filled with data?

=== EDIT

Just a small add on - I call the method loadInitialData in viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()
    mapView.delegate = self
    loadInitialData()
}

回答1:


You may want to use NSOperation. It's API has method addDependency(:) that is just what you're looking for. The code might look like this:

let queue = NSOperationQueue()
var operations : [NSOperation] = []
RestApiManager.sharedInstance.getRequests { json in
    if let jsonData = json.array {
       for requestJSON in jsonData {
           let newOperation = NSBlockOperation {
               SingleRequest.fromJSON(requestJSON){

               let pin = FBAnnotation()
               pin.coordinate = CLLocationCoordinate2D(latitude: request.latitude, longitude: request.longitude)
               self.array.append(pin)

            } 
            operations.append(newOperation)
           }

         }
      }
    let finalOperation = NSBlockOperation() {
         ///array has been populated
         ///proceed with it
    }

    operations.forEach { $0.addDependency(finalOperation) }
    operations.append(finalOpeartion)
    operationQueue.addOperations(operations)
 }


来源:https://stackoverflow.com/questions/35633199/how-can-i-add-records-fetched-asynchronously-from-json-to-the-array-only-when-al

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!