Reputation: 455
I'm simply trying to show how far away the user is from the location but I can't seem to get anything being printed to my console. If I place the code in the viewDidLoad and manually put in the coordinates for "postLocations" I get the distance but I can't seem to get anything printed with the code I have currently.
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)
}
}
Upvotes: 1
Views: 128
Reputation: 1507
On viewDidLoad()
try accessing Firebase Database by calling this:
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
}
}
}
}
}
Upvotes: 0
Reputation: 1222
Try this code in the viewDidLoad
and check the print statement in the console whether the latitude and longitude is printed.
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)
}
}
Upvotes: 1
Reputation: 1222
You don't need to call the Firebase observer in the didUpdateLocations
.
You should call the Firebase observer in the viewDidLoad
so that you can fetch the user location from the Firebase Databse. After the observer observe the user location, you need to fetch the current location so that you can compare the 2 locations. Just try this.
Upvotes: 0