Như bạn có thể thấy, tôi nhận được một tệp JSON, phân tích cú pháp nó bằng SwiftyJSON và cố gắng trả về tổng thời gian, nhưng nó sẽ không cho phép tôi. Làm thế nào để tôi làm điều này?Swift: Làm thế nào để trả về một giá trị trong hàm urlsession không đồng bộ?
func googleDuration(origin: String, destination: String) -> Int{
// do calculations origin and destiantion with google distance matrix api
let originFix = origin.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil);
let destinationFix = destination.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil);
let urlAsString = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+originFix+"&destinations="+destinationFix;
println(urlAsString);
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
let task = urlSession.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
println("parsing JSON");
let json = JSON(data: data);
if (json["status"].stringValue == "OK") {
if let totalTime = json["rows"][0]["elements"][0]["duration"]["value"].integerValue {
println(totalTime);
}
}
})
task.resume();
}
btw, thay vì chỉ thay thế không gian với '+', bạn có thể xem xét thực hiện một lối thoát trăm thích hợp, như được nêu ở đây http://stackoverflow.com/a/24888789/1271826 – Rob