【问题标题】:How do I assign a class property within a closure in swift 4如何在 swift 4 的闭包中分配类属性
【发布时间】: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


【解决方案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( .... )
    }
})

【讨论】:

    猜你喜欢
    • 2019-07-24
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多