[英]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. 我正在开发苹果地图的市场集群(这是插件https://github.com/ribl/FBAnnotationClusteringSwift ),我想一次在地图上显示所有记录-为此,我需要下载所有记录从远程Web服务中,将其添加到json(我已经完成了),然后将所有获取的点添加到数组中。
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: 如您所见,我将所有
pin
附加到数组,有时需要在这里使用此数组:
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. 我以为我可以在方法
loadInitialData
最后写上面的行,但是数组仍然为空。 How should I change my code so that it invokes the addAnnotations
method when the array
is filled with data? 我应该如何更改代码,以便在
array
充满数据时调用addAnnotations
方法?
=== EDIT ===编辑
Just a small add on - I call the method loadInitialData
in viewDidLoad
只是一个很小的附加-我在
viewDidLoad
调用方法loadInitialData
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
loadInitialData()
}
You may want to use NSOperation
. 您可能要使用
NSOperation
。 It's API has method addDependency(:)
that is just what you're looking for. 它的API具有方法
addDependency(:)
,这正是您所需要的。 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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.