【问题标题】:Add annotation after retrieving users latitude and longitude from Firebase从 Firebase 检索用户纬度和经度后添加注释
【发布时间】:2016-09-27 20:37:48
【问题描述】:

在从 Firebase 检索到所有在线用户的纬度和经度后,我正在尝试添加所有在线用户的 mapView 注释。我可以将其打印为可选或 CLLocationDegrees aka Double,但是当我尝试将其添加到我的 user.userAnnotation 属性中时,我得到了一个致命错误。这就是我要打印的内容:

this is the users lat Optional(19.435477800000001) 
this is the user latitude in CLLocationDegrees 19.4354778 
fatal error: unexpectedly found nil while unwrapping an Optional value

这是我的功能:

func fetchOnlineUsers() {
    ref = FIRDatabase.database().reference()

    FIRDatabase.database().reference().child("users").observe(.childAdded, with: { (snapshot) in

        if let dictionary = snapshot.value as? [String: AnyObject] {
            let user = AppUser()
            user.userEmail = (snapshot.value as? NSDictionary)?["name"] as? String
            user.latitude = (snapshot.value as? NSDictionary)?["latitude"] as? Double
            user.longitude = (snapshot.value as? NSDictionary)?["longitude"] as? Double
            user.online = ((snapshot.value as? NSDictionary)?["online"] as? Bool)!
            print("this is the user latitude \(user.latitude)")
            let userLat = CLLocationDegrees(user.latitude!)
            let userLon = CLLocationDegrees(user.longitude!)  

            if user.online == true {
                user.userAnnotation.coordinate = CLLocationCoordinate2D(latitude: userLat, longitude: userLon)

                self.users.append(user)
            }
            print("this are the users \(self.users)")
            print("this is the dictionary \(dictionary)")

            self.mainMapView.addAnnotations([user.userAnnotation])
        }
    }, withCancel: nil)
}

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database mapkit


    【解决方案1】:

    嗯,你得到的一些价值是nil。试试这个:

    guard let dictionary = snapshot.value as? [String: AnyObject],
    let email = (snapshot.value as? NSDictionary)?["name"] as? String,
    let latitude = (snapshot.value as? NSDictionary)?["latitude"] as? Double,
    let longitude = (snapshot.value as? NSDictionary)?["longitude"] as? Double,
    let online = ((snapshot.value as? NSDictionary)?["online"] as? Bool)! else { // Some error }
    

    如果成功,您可以开始使用在 guard let 中创建的变量,它们将 1:有值,2:不是可选的。

    【讨论】:

    • 嗨,我用一些缺失的代码更新了这个问题。我认为你的答案仍然有效。我现在去看看。
    • @cosmos,检查答案是否对您有帮助,否则请告诉我。
    • 好吧,如果您点击else,那么您的价值就会有问题。您可以在那里返回/继续,或者检查哪个值失败。
    • 好的,所以现在我在 let online = ... 中遇到了一个错误,它说条件绑定的初始化程序必须具有可选类型而不是 Bool
    • 返回真/假还是0/1?
    猜你喜欢
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多