为了账号安全,请及时绑定邮箱和手机立即绑定

Swift:如何在异步urlsession函数中返回值?

/ 猿问

Swift:如何在异步urlsession函数中返回值?

慕田峪9158850 2019-10-21 14:46:35

如您所见,我正在接收一个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();

}


查看完整描述

3 回答

?
慕斯王

您应该添加自己的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     

    }

}


查看完整回答
反对 回复 2019-10-21
?
摇曳的蔷薇

另一个例子:


   class func getExchangeRate(#baseCurrency: String, foreignCurrency:String, completion: ((result:Double?) -> Void)!){

    let baseURL = kAPIEndPoint

    let query = String(baseCurrency)+"_"+String(foreignCurrency)


    var finalExchangeRate = 0.0

    if let url = NSURL(string: baseURL + query) {

        NSURLSession.sharedSession().dataTaskWithURL(url) { data, response, error in


            if ((data) != nil) {

                let jsonDictionary:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSDictionary


                if let results = jsonDictionary["results"] as? NSDictionary{

                    if let queryResults = results[query] as? NSDictionary{

                        if let exchangeRate = queryResults["val"] as? Double{

                            let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT

                            dispatch_async(dispatch_get_global_queue(priority, 0)) {

                                dispatch_async(dispatch_get_main_queue()) {

                                    completion(result: exchangeRate)

                                }

                            }


                        }

                    }

                }

            }

            else {

                completion(result: nil)

            }


        }.resume()

    }

}

呼叫:


 Currency.getExchangeRate(baseCurrency: "USD", foreignCurrency: "EUR") { (result) -> Void in

        if let exchangeValue = result {

            print(exchangeValue)

        }

    }


查看完整回答
反对 回复 2019-10-21
?
翻翻过去那场雪

另一个例子:


func getJason(url: NSURL, completionHandler: (String?, NSError?) -> Void ) -> NSURLSessionTask {


    var finalData: String!

    let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in


        if error != nil{


            completionHandler(nil, error)

            return

        }

        else{


        if let urlContent = data{


            do{

                let jsonData = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers)


                if let ip = jsonData["ip"]{


                    finalData = ip as? String

                    completionHandler(finalData, nil)

                    return

                }


            }catch{

                print("EMPTY")

            }


        }


    }

}

    task.resume()

    return task

}

然后我在viewDidLoad中调用了它


getJason(url) { (ipAddress, error) -> Void in


        if error != nil{


            print(error)

        }

        else{

            if let ip = ipAddress{          //To get rid of optional


        self.ipLabelDisplay.text = "Your Ip Address is: \(ip)"


            }


        }

    }


查看完整回答
反对 回复 2019-10-21

添加回答

回复

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信