仅当所有记录都在Swift中获取时,如何才能将从json异步获取的记录添加到数组中? [英] How can I add records fetched asynchronously from json to the array only when all records are fetched in Swift?
问题描述
我正在开发苹果地图的市场集群(这是插件 https://github.com/ribl/FBAnnotationClusteringSwift ),我想一次在地图上显示所有记录-为此,我需要从远程Web服务下载所有记录,将其添加到json(我已经完成了),然后添加所有指向数组.
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.
我的代码如下:
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)
}
})
}
}
}
}
如您所见,我将所有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)
我以为我可以在方法loadInitialData
的最后写上面的行,但是数组仍然是空的.我应该如何更改代码,以便在array
充满数据时调用addAnnotations
方法?
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?
===编辑
只是一个小小的补充-我在viewDidLoad
Just a small add on - I call the method loadInitialData
in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
loadInitialData()
}
推荐答案
您可能要使用NSOperation
. API的方法addDependency(:)
正是您要寻找的.
代码可能看起来像这样:
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)
}
这篇关于仅当所有记录都在Swift中获取时,如何才能将从json异步获取的记录添加到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!