您不能直接从异步任务返回数据。
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)}


