Swift 中的同步代码执行

Synchronous code execution in Swift

我正在传递一组要进行反向地理编码的纬度和经度坐标。反向地理编码有效,我取回了我的地址数据,但随后我需要根据该数据创建一个 URL,我会进一步向下操作。我发现 NSURLSession 在我取回数据之前正在执行。您可以看到我在 println 中放置的位置以显示 "first" 和 "second",但是当我执行此代码时在输出控制台中显示 "second",然后显示 "first" 以及地址数据,告诉我我没有按顺序 运行ning。

如何强制执行顺序,要求我的变量 addchunk 在 NSURLSession 获取 运行 之前存在?

谢谢!

@IBAction func grabData(sender: UIButton) {
    var latitude:CLLocationDegrees = (latitudeEntry.text as NSString).doubleValue
    var longitude:CLLocationDegrees = (longitudeEntry.text as NSString).doubleValue
    var location = CLLocation(latitude: latitude, longitude: longitude)

    // reverse geocodes the supplied latitude and longitude
    CLGeocoder().reverseGeocodeLocation(location, completionHandler: {
        (placemarks, error) -> Void in
        if error != nil {
            println("Reverse geocoder failed with error" + error.localizedDescription)
        }
        if placemarks.count > 0 {
            let pm = placemarks[0] as CLPlacemark
            self.addchunk = "\(pm.subThoroughfare)-\(pm.thoroughfare),-\(pm.locality),-\(pm.administrativeArea)".lowercaseString
            println("first " + self.addchunk)
        } else {
            println("Problem with the data received from geocoder")
        }
    })

    var url = NSURL(string: "http://www.example.com/" + addchunk)
    println("second " + addchunk)
    if url != nil {
        let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: {
            (data, response, error) -> Void in
    ...

像这样更新您的代码:

var latitude:CLLocationDegrees = ("-34.4232722" as NSString).doubleValue
    var longitude:CLLocationDegrees = ("150.8865837" as NSString).doubleValue
    var location = CLLocation(latitude: latitude, longitude: longitude)

    // reverse geocodes the supplied latitude and longitude
    CLGeocoder().reverseGeocodeLocation(location, completionHandler: {
        (placemarks, error) -> Void in
        if error != nil {
            println("Reverse geocoder failed with error" + error.localizedDescription)
        }
        if placemarks.count > 0 {
            let pm = placemarks[0] as CLPlacemark
            self.addchunk = "\(pm.subThoroughfare)-\(pm.thoroughfare),-\(pm.locality),-\(pm.administrativeArea)".lowercaseString
            println("first " + self.addchunk)
        } else {
            println("Problem with the data received from geocoder")
        }
        var url = NSURL(string: "http://www.example.com/" + self.addchunk)
        println("second " + self.addchunk)
        if url != nil {
            let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: {
                (data, response, error) -> Void in
            })
        }
    })

我已经测试了它及其工作 fine.and 这是我坐标的输出:

first 18-hercules street,-wollongong,-nsw
second 18-hercules street,-wollongong,-nsw