Search code examples
swiftfirebasefirebase-realtime-databasegeofire

Save geoFire location under random firebase id swift 4


I'm trying to save the geofire information under each postId but currently not quite sure how to do so. Could someone please help me figure out how to save the information under the postId node.

        @objc func handlePost() {

    navigationItem.rightBarButtonItem?.isEnabled = false

    guard let uid = Auth.auth().currentUser?.uid else { return }

    guard let caption = textView.text, caption.characters.count > 0 else { return }

    let userPostRef = Database.database().reference().child("posts").child(uid)

    let ref = userPostRef.childByAutoId()

    guard let locationName = locationNameButton.titleLabel?.text else { return }

    let latitude = lat
    let longitude = long

    let geoLatitude = (latitude as! NSString).doubleValue
    let geoLongitude = (longitude as! NSString).doubleValue

    geoFireRef = Database.database().reference().child("posts").child(uid)
    geoFire = GeoFire(firebaseRef: geoFireRef)

    let values = ["caption": caption,"locationName": locationName, "latitude": latitude,"longitude": longitude,"creationDate": Date().timeIntervalSince1970] as [String : Any]

    geoFire?.setLocation(CLLocation(latitude: geoLatitude, longitude: geoLongitude), forKey: ref.key!)

Post and UID node


Solution

  • If you want to store the geolocation under the same key as

    let ref = userPostRef.childByAutoId()
    

    You can simply get the key property from ref. So:

    geoFire?.setLocation(CLLocation(latitude: geoLatitude, longitude: geoLongitude), forKey: ref.key)