【发布时间】:2018-01-16 18:02:23
【问题描述】:
我是 Swift 3 的新手,我有一个问题是关于确定相对于用户位置的坐标是否在附近。之后,我想将附近的位置显示到 TableView 中。
这是我的 Firebase 结构:
我的班级是这样的:
class UITableViewControllerForShop: UIViewController, UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate
这些变量是全局的:
let databaseRef = FIRDatabase.database().reference().child("Butikker")
var retrieveData = [String:AnyObject]()
var distanceInMeters: CLLocationDistance!
在我的 viewDidLoad 函数中我执行这个:
override func viewDidLoad() {
super.viewDidLoad()
databaseRef.observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! FIRDataSnapshot
let dictionary = snap.value as! [String: AnyObject]
self.retrieveData = ["latitude": dictionary["Latitude"] as! Double as AnyObject, "longtitude": dictionary["Longtitude"] as! Double as AnyObject]
}
})
}
要检查用户位置并将其与 Firebase 位置进行比较,我执行以下操作:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
print(location.coordinate.latitude, location.coordinate.longitude)
//My location
let myCoordinate = CLLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
if self.retrieveData.isEmpty == false {
let shopCoordinate = CLLocation(latitude: retrieveData["latitude"]! as! CLLocationDegrees, longitude: retrieveData["longtitude"]! as! CLLocationDegrees)
print(shopCoordinate.coordinate.latitude, shopCoordinate.coordinate.longitude)
distanceInMeters = myCoordinate.distance(from: shopCoordinate)
print(distanceInMeters)
}
//Distance
}
我像这样初始化我的表格视图:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
if distanceInMeters > 5000 {
cell.textLabel?.text = retrieveData["latitude"] as! String
}
return cell
}
这些是我遇到的问题:
- 在 locationManager 函数中初始化后,我不知道如何检查我的距离是否 > 5000。
- 我的字典 retrieveData 不会为每个键存储超过 1 个值,如果我想在 tableview 中显示附近项目的列表,这会导致问题。
- 遍历 for in 循环需要时间,这使得获取一切变得更加困难。
我想回答的问题:
1.distanceInMeters在locationManager函数中初始化后如何使用?
2.如何判断附近是否有东西并放入我的TableView?
【问题讨论】:
标签: swift dictionary firebase firebase-realtime-database latitude-longitude