栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

斯威夫特:如何在异步urlsession函数中返回值?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

斯威夫特:如何在异步urlsession函数中返回值?

您应该添加自己的

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, pre: kTotalTimeError, userInfo: nil) // populate this any way you prefer completionHandler(nil, totalTimeError)        }        let jsonError = NSError(domain: kAppDomain, pre: 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         }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/616353.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号