本文介绍了从Firebase检索用户的经度和纬度后添加注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to add a mapView annotation of all the online user after retrieving their latitude and longitude from Firebase. I am able to print it as an optional or as a CLLocationDegrees aka Double, but when I try to add it into my user.userAnnotation attribute I get a fatal error. This is what I am printing:

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)
}

推荐答案

您得到的一些值是nil.尝试以下方法:

Well some of the value/s that you´re getting is nil. Try this instead:

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:不是可选的.

If this succeeds you can start use the variables created in the guard let and they will 1: have a value, 2: not be Optional.

这篇关于从Firebase检索用户的经度和纬度后添加注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 04:36