简体   繁体   中英

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

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 pin s 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()
}

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)
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM