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

时间:2019-03-03 15:41:13

标签: swift core-location clgeocoder

我正在尝试访问位置数据,从中获取城市名称,然后将其分配给变量,这样我就可以在其他地方使用它了。它从闭包内部很好地打印了变量,但是当我尝试通过我创建的类变量访问它时,它的值为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")
        })
    }
}

1 个答案:

答案 0 :(得分:1)

var express = require('express'); var fs = require('fs'); var app = express(); var triggerURL = ''; //i'll send an http request to this adress to trigger the action from server var JSON = { item: "seeds", Answers: "5", richText: "<b>How can you reduce crop toxicity by turning plants upside down?</b><br/>Idea:<br/> Upside-down gardening is a hanging vegetable garden being the suspension of soil and seedlings of a kitchen garden to stop <b>pests</b> and blight,and eliminate the typical gardening tasks of tilling, weeding, and staking plants." } var port = process.env.PORT || 3000; var ListenPort = '8086'; // my port to recieve triggers var SendingPort = '4046'; // which unity will listen to var unity_url ='185.158.123.54:'+SendingPort; //fake IP, just for the example //triggerURL app.get('/', function(req,res){ var resp = JSON.stringify(JSON); var writable = fs.createWriteStream(); //res.json(JSON); //instead i wanna send it to unity_url; }); //app.listen(ListenPort); app.listen(port); 调用移到reverseGeocode闭包中:

db.collection("posts").document().setData