-2

Im trying to access the location data, from that get the city name and then assign it to a variable so I will be able to use it elsewhere. It prints the variable fine from within the closure but its nil when I try to access it through the class variable I've created, the code is below, thanks.

class NewPostViewController: BaseViewController {

    @IBOutlet weak var postBodyTextField: UITextField!

    var city: String?

    @IBAction func createPostAction(_ sender: Any) {
        getCity()

        db.collection("posts").document().setData([
            "body": postBodyTextField.text,
            "location": city,
            "user": user?.displayName
        ]) { err in
            if let err = err {
                print("Error writing document: \(err)")
            } else {
                print("Document successfully written!")
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func getCity() {
        Locator.currentPosition(accuracy: .city, onSuccess: { location in
            let geocoder: CLGeocoder = CLGeocoder()
            geocoder.reverseGeocodeLocation(location, completionHandler: { location, error in
                if let location = location {
                    self.city = location[0].locality
                }
            })
        }, onFail: {_,_ in
            print("Error, couldnt get current location")
        })
    }
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
Chris W
  • 13
  • 2
  • 1
    Think / google about what "asynchronous" means. Your code does not run in the order in which it is written. You are assigning _to_ `self.city` _after_ you try to fetch the value _from_ `self.city`. The line `"location": city` executes _before_ the line `self.city = location[0].locality`. – matt Mar 03 '19 at 15:46

1 Answers1

1

Move the db.collection("posts").document().setData call into the reverseGeocode closure:

geocoder.reverseGeocodeLocation(location, completionHandler: { location, error in
    if let location = location {
         self.city = location[0].locality
         db.collection("posts").document().setData( .... )
    }
})
Gereon
  • 17,258
  • 4
  • 42
  • 73