Add annotation after retrieving users latitude and longitude from Firebase

心已入冬 提交于 2019-12-25 09:22:32

问题


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

And this is my function:

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

回答1:


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 }

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.



来源:https://stackoverflow.com/questions/39733874/add-annotation-after-retrieving-users-latitude-and-longitude-from-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!