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

我如何从NSURLSession.sharedSession()。dataTaskWithRequest获取数据

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

我如何从NSURLSession.sharedSession()。dataTaskWithRequest获取数据

您不能直接从异步任务返回数据。

Swift 2的解决方案是使完成处理程序如下所示:

class PostFOrData {    // the completion closure signature is (NSString) -> ()    func forData(completion: (NSString) -> ()) {        if let url = NSURL(string: "http://210.61.209.194:8088/SmarttvWebServiceTopmsoApi/GetReadlist") { let request = NSMutableURLRequest( URL: url) request.HTTPMethod = "POST" let postString : String = "uid=59" request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {     data, response, error in     if let data = data,         jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)         where error == nil {  completion(jsonString)     } else {         print("error=(error!.localizedDescription)")     } } task.resume()        }    }}let pfd = PostFOrData()// you call the method with a trailing closurepfd.forData { jsonString in    // and here you get the "returned" value from the asynchronous task    print(jsonString)}

这样,仅当异步任务完成时才调用完成。这是一种无需实际使用即可“返回”数据的方法

return

Swift 3版本

class PostFOrData {    // the completion closure signature is (String) -> ()    func forData(completion:  @escaping (String) -> ()) {        if let url = URL(string: "http://210.61.209.194:8088/SmarttvWebServiceTopmsoApi/GetReadlist") { var request = URLRequest(url: url) request.httpMethod = "POST" let postString : String = "uid=59" request.httpBody = postString.data(using: String.Encoding.utf8) let task = URLSession.shared.dataTask(with: request) {     data, response, error in     if let data = data, let jsonString = String(data: data, encoding: String.Encoding.utf8), error == nil {         completion(jsonString)     } else {         print("error=(error!.localizedDescription)")     } } task.resume()        }    }}let pfd = PostFOrData()// you call the method with a trailing closurepfd.forData { jsonString in    // and here you get the "returned" value from the asynchronous task    print(jsonString)}


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

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

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