如何在swift 4中的闭包中分配类属性

问题描述 投票:-2回答:1

我试图访问位置数据,从中获取城市名称,然后将其分配给变量,以便我可以在其他地方使用它。它从闭包内打印变量fine但是当我尝试通过我创建的类变量访问它时它是nil,代码在下面,谢谢。

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")
        })
    }
}
swift core-location clgeocoder
1个回答
1
投票

db.collection("posts").document().setData调用移动到reverseGeocode闭包中:

geocoder.reverseGeocodeLocation(location, completionHandler: { location, error in
    if let location = location {
         self.city = location[0].locality
         db.collection("posts").document().setData( .... )
    }
})
© www.soinside.com 2019 - 2024. All rights reserved.