【发布时间】:2019-03-03 15:41:12
【问题描述】:
我正在尝试访问位置数据,从中获取城市名称,然后将其分配给一个变量,以便我可以在其他地方使用它。它从闭包内打印出变量很好,但是当我尝试通过我创建的类变量访问它时它为零,代码如下,谢谢。
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")
})
}
}
【问题讨论】:
-
想想/谷歌什么是“异步”。您的代码未按编写顺序运行。您正在分配 to
self.city您尝试从self.city获取值。"location": city行 在self.city = location[0].locality行之前执行。
标签: swift core-location clgeocoder