Search code examples
swiftcore-locationclgeocoder

How do I assign a class property within a closure in swift 4


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")
        })
    }
}

Solution

  • 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( .... )
        }
    })