无法从Firebase数据库Swift 4中获取数据

时间:2018-11-05 01:51:47

标签: swift firebase firebase-realtime-database swift4

我只是试图显示用户离该位置有多远,但似乎无法将任何内容打印到我的控制台上。如果我将代码放在viewDidLoad中,然后手动将其放置在“ postLocations”的坐标中 我知道了,但是我似乎无法用当前的代码打印任何内容。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation: CLLocation = locations[0] as CLLocation

    let ref = Database.database().reference().child("posts")
    ref.observeSingleEvent(of: .value, with: { (snapshot) in

        guard let dictionary = snapshot.value as? [String: AnyObject] else { return }

        guard let latitude = dictionary["latitude"] as? Double else { return }
        guard let longitude = dictionary["longitude"] as? Double else { return }

        let currentLocation = Coordinate(long: userLocation.coordinate.longitude, lat: userLocation.coordinate.latitude)
        let postLocations = Coordinate(long: longitude, lat: latitude)

        if currentLocation.distance(to: postLocations) <= 100 {
            print("You are \(currentLocation.distance(to: postLocations)) away from posts")
        } else {
            print("No posts in area")
        }

    }) { (error) in
        print("There was an error getting posts", error)
    }

    }

Firebase Database

3 个答案:

答案 0 :(得分:1)

viewDidLoad中尝试此代码,并在控制台中检查print语句是否打印了纬度和经度。

func fetchUserLocation() {
     let ref = Database.database().reference().child("posts")
     ref.observeSingleEvent(of: .value, with: { (snapshot) in
     guard let dictionary = snapshot.value as? [String: AnyObject] else { return }
     guard let latitude = dictionary["latitude"] as? String else { return }
     guard let longitude = dictionary["longitude"] as? String else { return }
     print("lat: \(latitude), lon: \(longitude)")
   }) { (error) in
    print("There was an error getting posts", error)
  }
}

答案 1 :(得分:0)

您无需在didUpdateLocations中调用Firebase观察器。 您应该在viewDidLoad中调用Firebase观察器,以便可以从Firebase数据库获取用户位置。观察者观察用户位置后,您需要获取当前位置,以便可以比较这两个位置。尝试一下。

答案 2 :(得分:0)

viewDidLoad()上,尝试通过调用以下命令访问Firebase数据库:

func getFirebaseUserLocation() {
    let ref = Database.reference(withPath: "posts")
    ref.observe(.value, with: { (snapshot) in
        for child in snapshot.children {
            if let postSnapshots = child as? DataSnapshot  { 
                for postSnapshot in postSnapshots.children {
                    guard let postDictionary = postSnapshot.value as? [String: Any] else { return }
                    guard let latitude = postDictionary["latitude"] as? String, let longitude = postDictionary["longitude"] as? String else { return } 
                    print(latitude, longitude)
                    // here you can access your latitude and longitude as Strings from Firebase Database
                }
            }
        }
    }
}