我正在通过一组纬度和经度坐标进行反向地理编码。反向地理编码工作,我收回我的地址数据,但我需要从该数据创建一个URL,我做了更进一步。我发现的是NSURLSession在我获取数据之前正在执行。您可以看到我在println中放置的位置显示“first”和“second”,但是在执行此代码的输出控制台中,“second”显示然后“first”以及地址数据,这告诉我'我没有按顺序跑。
如何强制执行命令,要求在NSURLSession运行之前存在变量addchunk?
谢谢!
@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
...
答案 0 :(得分:2)
更新您的代码:
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
})
}
})
我已经测试了这个并且工作正常。这是我坐标的输出:
first 18-hercules street,-wollongong,-nsw
second 18-hercules street,-wollongong,-nsw