gpt4 book ai didi

ios - 从 Firebase 数据库在 MKMapView 上放置多个标记

转载 作者:搜寻专家 更新时间:2023-10-31 22:17:58 26 4
gpt4 key购买 nike

我正在创建一个 iOS 应用程序,它使用 Apple map 来显示本地车库/庭院销售的标记。到目前为止,我已经能够弄清楚如何从 Firebase 数据库中在 Apple Maps 上放置一个标记,但我不确定如何使用多个标记来做到这一点。我已经完成了类似的任务,使用单元格在 Firebase 数据库的 UITableView 中显示不同的内容,但这是我第一次以 map 方式进行。我在读一篇文章here这显示了如何使用 JSON 数据,但由于标记信息将是实时的,我的应用程序不可能那样做。将多个标记添加到 MKMapView 的最佳方法是什么?

来自 ViewController 的片段(仅设置一个标记)

Database.database().reference().child("posts").observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let artwork = Artwork(title: dictionary["title"] as! String,
locationName: dictionary["location"] as! String,
discipline: dictionary["category"] as! String,
coordinate: CLLocationCoordinate2D(latitude: dictionary["lat"] as! Double, longitude: dictionary["long"] as! Double))
self.mapView.addAnnotation(artwork)
}
})

艺术品.swift

class Artwork: NSObject, MKAnnotation {
let title: String?
let locationName: String
let discipline: String
let coordinate: CLLocationCoordinate2D

init(title: String, locationName: String, discipline: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.locationName = locationName
self.discipline = discipline
self.coordinate = coordinate

super.init()
}

var subtitle: String? {
return locationName
}
}

最佳答案

多亏了 link,我才能够找到解决这个问题的方法@kosuke-ogawa 发布。

ViewController.swift 中的片段

override func viewDidLoad() {
super.viewDidLoad()
let ref = Database.database().reference()
let postsRef = ref.child("posts")
postsRef.observeSingleEvent(of: .value, with: { (snapshot) in
for snap in snapshot.children {
let postSnap = snap as! DataSnapshot
if let dict = postSnap.value as? [String:AnyObject] {
let title = dict["title"] as! String
let locationName = dict["location"] as! String
let discipline = dict["category"] as! String
let coordinate = CLLocationCoordinate2D(latitude: dict["lat"] as! Double, longitude: dict["long"] as! Double)
let artwork = Artwork(title: title, locationName: locationName, discipline: discipline, coordinate: coordinate)
self.mapView.addAnnotation(artwork)
}
}
})
}

如果有更简洁的方法来执行此操作,请随时编辑我的代码以在将来帮助其他人。

关于ios - 从 Firebase 数据库在 MKMapView 上放置多个标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50322679/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com