斯威夫特:我如何异步urlsession函数中返回一个值? [英] Swift: How do I return a value within an asynchronous urlsession function?

查看:334
本文介绍了斯威夫特:我如何异步urlsession函数中返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如你所看到的,我收到一个JSON文件,使用SwiftyJSON解析它,并试图返回TOTALTIME,但它不会让我。我该怎么做呢?

  FUNC googleDuration(来源:字符串,目的地:字符串) -  GT; INT {
    //做计算的起源和​​destiantion与谷歌的距离矩阵API    让originFix = origin.stringByReplacingOccurrencesOfString(,withString:+,选项:NSStringCompareOptions.LiteralSearch,范围:无);
    让destinationFix = destination.stringByReplacingOccurrencesOfString(,withString:+,选项:NSStringCompareOptions.LiteralSearch,范围:无);    让urlAsString = \"https://maps.googleapis.com/maps/api/distancematrix/json?origins=\"+originFix+\"&destinations=\"+destinationFix;
    的println(urlAsString);    让URL = NSURL(字符串:urlAsString)!
    让urlSession = NSURLSession.sharedSession()    让任务= urlSession.dataTaskWithURL(URL,completionHandler:{数据,回应,误差 - >无效的
        如果错误!= {为零
            //如果在Web请求一个错误,它打印到控制台
            的println(error.localizedDescription)
        }        的println(JSON解析);
        让JSON = JSON(数据:数据);
        如果(JSON [身份。stringValue的==OK){
            如果让TOTALTIME = json的[行] [0] [元素] [0] [时间] [价值。integerValue {
                的println(TOTALTIME);
            }
        }
    })
    task.resume();
}


解决方案

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

  FUNC googleDuration(来源:字符串,目的地:字符串,completionHandler:(智力?NSError) -  GT;无效) -  GT; NSURLSessionTask {
    //做计算的起源和​​destiantion与谷歌的距离矩阵API    让originFix = origin.stringByReplacingOccurrencesOfString(,withString:+,选项:NSStringCompareOptions.LiteralSearch,范围:无);
    让destinationFix = destination.stringByReplacingOccurrencesOfString(,withString:+,选项:NSStringCompareOptions.LiteralSearch,范围:无);    让urlAsString = \"https://maps.googleapis.com/maps/api/distancematrix/json?origins=\"+originFix+\"&destinations=\"+destinationFix
    的println(urlAsString)    让URL = NSURL(字符串:urlAsString)!
    让urlSession = NSURLSession.sharedSession()    让任务= urlSession.dataTaskWithURL(URL){数据,回应,误差 - >在无效
        如果错误!= {为零
            //如果在Web请求一个错误,它打印到控制台
            //的println(error.localizedDescription)
            completionHandler(零,错误)
            返回
        }        //的println(JSON解析);
        让JSON = JSON(数据:数据)
        如果(JSON [身份。stringValue的==OK){
            如果让TOTALTIME = json的[行] [0] [元素] [0] [时间] [价值。integerValue {
                //的println(TOTALTIME);
                completionHandler(TOTALTIME,无)
                返回
            }
            让totalTimeError = NSError(域名:kAppDomain,code:kTotalTimeError,USERINFO:无)//填充这个什么办法preFER
            completionHandler(零,totalTimeError)
        }
        让jsonError = NSError(域名:kAppDomain,code:kJsonError,USERINFO:无)//再次,填充这个你preFER
        completionHandler(零,jsonError)
    }
    task.resume()
    返回任务
}

我也有这个返回 NSURLSessionTask 在调用者希望能够取消任务情况。

总之,你会调用这个像这样:

  googleDuration(始发地,目的地:目的地){TOTALTIME,错误
    如果让TOTALTIME = {TOTALTIME
        //使用TOTALTIME这里
    }其他{
        //处理错误
    }
}

As you can see, I'm receiving a JSON file, parsing it using SwiftyJSON, and trying to return totalTime, but it won't let me. How do I do this?

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

解决方案

You should add your own completionHandler closure parameter and call it when the task completes:

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
}

I'd also have this return the NSURLSessionTask in case the caller wants to be able to cancel the task.

Anyway, you'd call this like so:

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

这篇关于斯威夫特:我如何异步urlsession函数中返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆