Chris
Chris

Reputation: 68

GeoFire with Swift

I plan to use GeoFire to filter my firebase data based on location. Not sure how to get started with this because I just started developing. I have a pic and a caption etc that I create in one Class with:

    @IBAction func shareDidTap(_ sender: Any) {
            if let image = image, let caption = textView.text {
                let newMedia = Media(type: "image", caption: caption, createdBy: user, image: image)
                    newMedia.save(completion: { (error) in
                        if let error = error {
                            self.alert(title: "Oops!", message: error.localizedDescription, buttonTitle: "OK")
                        } else {
                            self.user.share(newMedia: newMedia)

in a separate "User" class (MVC) I save it into Firebase with

    func share(newMedia: Media) {
            DatabaseReference.users(uid: uid).reference().child("media").childByAutoId().setValue(newMedia.uid)
        }

Where do I instantiate the GeoFire reference? Do I have to use Core Location to get my own Lat and Lon? Any help would be appreciated. Thank you.

Upvotes: 2

Views: 2822

Answers (1)

Niall Kiddle
Niall Kiddle

Reputation: 1487

Adding GeoFire

Install with pods pod 'GeoFire', :git => 'https://github.com/firebase/geofire-objc.git'

Then import to project import GeoFire

Create a reference to it using

let rootRef = Database.database().reference()
let geoRef = GeoFire(firebaseRef: rootRef.child("user_locations"))

To get the current user location you can use Location manager via cocoa pods: https://github.com/varshylmobile/LocationManager

I am guessing you want the media saved on the database to have a location. You then use GeoFire to save the location using GeoFire.setlocation Call this when you save your post to the database, GeoFire handles the database structure of adding locations using your post ID.

an example:

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

You then query the database of locations using CircleQuery You can give a radius of how far you want to query the database within from a given location (user location)

an example:

let query = geoRef.query(at: userLocation, withRadius: 1000)

query?.observe(.keyEntered, with: { key, location in
    guard let key = key else { return }
    print("Key: " + key + "entered the search radius.")
})

A really good tutorial that I used was: https://www.youtube.com/watch?v=wr19iKENC-k&t=600s

Look on their channel and query GeoFire for other videos that might help you further.

Upvotes: 1

Related Questions