2016-09-27 35 views
0

我想從Firebase中檢索所有在線用戶的緯度和經度後,添加所有在線用戶的mapView註釋。我可以打印它作爲一個可選或作爲一個CLLocationDegrees aka Double,但是當我嘗試將它添加到我的user.userAnnotation屬性中時,我得到一個致命錯誤。這就是我打印:從Firebase中檢索用戶經度和緯度後添加註釋

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

回答

1

好一些價值/ s的那you're得到的是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:不可選。

+0

嗨,我更新了一些缺少代碼的問題。我認爲你的答案仍然可以工作。我會現在檢查。 – cosmos

+0

@cosmos,檢查答案是否可以幫助你,否則請告訴我。 –

+0

那麼如果你點擊'else',那麼你就有一些問題。你可以在那裏返回/繼續,或者檢查失敗的值。 –