
class PostFOrData { let url = NSURL( string: "http://210.61.209.194:8088/SmarttvWebServicetopmsoAPI/GetReadList") var picUrl = NSURL(string : "http://210.61.209.194:8088/SmarttvMedia/img/epi00001.png") var responseString : Nsstring = "" func forData() -> Nsstring { let request = NSMutableURLRequest( URL: url!) request.httpMethod = "POST" var s : Nsstring = "" let poststring : String = "uID=59" request.httpBody = poststring.dataUsingEnCoding(NSUTF8StringEnCoding) let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data,response,error in if error != nil { println("error=\(error)") return } else { println("response = \(response!)") self.responseString = Nsstring(data: data,enCoding: NSUTF8StringEnCoding)! println("responseString = \(self.responseString)") } } // I want to return Nsstring here,but I always get nothing return self.responseString }} 您不能直接从异步任务返回数据. 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,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)} 这样,只有当异步任务完成时才调用完成.这是一种“返回”数据而不实际使用返回的方式.
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,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)} 总结 以上是内存溢出为你收集整理的swift – 如何从NSURLSession.sharedSession()获取数据dataTaskWithRequest全部内容,希望文章能够帮你解决swift – 如何从NSURLSession.sharedSession()获取数据dataTaskWithRequest所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)