GeoFire Swift 3 - Saving and Updating Coordinates

≯℡__Kan透↙ 提交于 2019-12-02 19:52:28

This is my Firebase DB structure for update users location by time and retrive the nearby users to show on map:

db-root
"users" : {
    <userUID> : {
        "someKey" : "someValue",
        ...
    }
}
"users_location" : {
    <userUID> : {
        <geofireData> ...
    }
}

Vars to use:

let ref = FIRDatabase.database().reference()
let geoFire = GeoFire(firebaseRef: ref.child("users_location"))

To update logged user location:

func updateUserLocation() {

    if let myLocation = myLocation {

        let userID = FIRAuth.auth()!.currentUser!.uid
        geoFire!.setLocation(myLocation, forKey: userID) { (error) in
            if (error != nil) {
                debugPrint("An error occured: \(error)")
            } else {
                print("Saved location successfully!")
            }
        }

    }
}

To find nearby user I use the findNearbyUsers function. It' useful to find the nearby users and save into nearbyUsers array the UID key of the the users. The observeReady function is executed after the query completion and uses the UID to retrieve the users details (I use this to show users details on map).

func findNearbyUsers() {

    if let myLocation = myLocation {

        let theGeoFire = GeoFire(firebaseRef: ref.child("users_location"))
        let circleQuery = theGeoFire!.query(at: myLocation, withRadius: radiusInMeters/1000)

        _ = circleQuery!.observe(.keyEntered, with: { (key, location) in

            if !self.nearbyUsers.contains(key!) && key! != FIRAuth.auth()!.currentUser!.uid {
                self.nearbyUsers.append(key!)
            }

        })

        //Execute this code once GeoFire completes the query!
        circleQuery?.observeReady({

            for user in self.nearbyUsers {

                self.ref.child("users/\(user)").observe(.value, with: { snapshot in
                    let value = snapshot.value as? NSDictionary
                    print(value)
                })
            }

        })

    }

}

Hope it helps

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