json - Swift:如何在异步 urlsession 函数中返回一个值?

标签 json asynchronous swift nsurlsession

如您所见,我正在接收一个 JSON 文件,使用 SwiftyJSON 对其进行解析,并尝试返回 totalTime,但它不允许我这样做。我该怎么做?

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();
}

最佳答案

您应该添加自己的completionHandler 闭包参数并在任务完成时调用它:

func googleDuration(origin: String, destination: String, completionHandler: (Int?, NSError?) -> Void ) -> NSURLSessionTask {
    // 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) { 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)
            completionHandler(nil, error)
            return
        }

        //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);
                completionHandler(totalTime, nil)
                return
            }
            let totalTimeError = NSError(domain: kAppDomain, code: kTotalTimeError, userInfo: nil) // populate this any way you prefer
            completionHandler(nil, totalTimeError)
        }
        let jsonError = NSError(domain: kAppDomain, code: kJsonError, userInfo: nil) // again, populate this as you prefer
        completionHandler(nil, jsonError)
    }
    task.resume()
    return task
}

如果调用者希望能够取消任务,我也会让它返回 NSURLSessionTask

无论如何,你会这样调用它:

googleDuration(origin, destination: destination) { totalTime, error in
    if let totalTime = totalTime {
        // use totalTime here
    } else {
        // handle error     
    }
}

关于json - Swift:如何在异步 urlsession 函数中返回一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47155763/

相关文章:

javascript - 如何使 jquery CSS 操作同步(即没有回调)?

c# - MongoDB .NET 驱动程序查找全部 : How to write it better?

ios - 使用 Swift 每周重复本地通知

ios - 使用像素数据从 SKTexture 创建 SKSpriteNode

swift - 如何在类型别名中使用类型参数?

javascript - ER_JSON_USED_AS_KEY : JSON column 'parent_ids' supports indexing only via generated columns on a specified JSON path

javascript - 将 PHP 解析的 JSON 数据从 MySQL 提供给 Morris.js Chart

json - alamofire 解析嵌套的 json

javascript - 使用 JQuery 解析嵌套的 JSON

google-chrome - 缺少 Google Chrome 开发工具上的异步复选框