IPhone : Synchronous code execution in Swift

on Sunday, February 22, 2015

I'm passing a set of latitude and longitude coordinates to be reverse geocoded. The reverse geocoding works and I get back my address data, but I then need to create a URL from that data, which I do further down. What I'm finding is that the NSURLSession is executing before I get my data back. You can see where I put in the println to display "first" and "second", but in the output console when I execute this code, "second" displays and then "first" along with the address data, which tells me I'm not running in order.


How can I force the order of the execution, requiring my variable addchunk to exist before the NSURLSession gets run?


Thanks!



@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 comments:

Post a Comment