如何在swift 4中的闭包中指定类属性
我试图访问位置数据,从中获取城市名称,然后将其分配给一个变量,这样我就可以在其他地方使用它。它可以在闭包中很好地打印变量,但是当我试图通过我创建的类变量访问它时,它的值为零,代码如下,谢谢如何在swift 4中的闭包中指定类属性,swift,core-location,clgeocoder,Swift,Core Location,Clgeocoder,我试图访问位置数据,从中获取城市名称,然后将其分配给一个变量,这样我就可以在其他地方使用它。它可以在闭包中很好地打印变量,但是当我试图通过我创建的类变量访问它时,它的值为零,代码如下,谢谢 class NewPostViewController: BaseViewController { @IBOutlet weak var postBodyTextField: UITextField! var city: String? @IBAction func create
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")
})
}
}
将
db.collection(“posts”).document()
geocoder.reverseGeocodeLocation(location, completionHandler: { location, error in
if let location = location {
self.city = location[0].locality
db.collection("posts").document().setData( .... )
}
})
想想/google“异步”是什么意思。您的代码没有按照编写顺序运行。尝试从self.city
获取值后,您将分配给self.city
。行“location”:city
在行self.city=location[0]之前执行。locality
。