如何使用return fetched string
编写post方法func post(link:String,passedPostString:String) {
let request = NSMutableURLRequest(url: NSURL(string: link)! as URL)
request.httpMethod = "POST"
request.httpBody = passedPostString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(String(describing: error))")
print("******Error*****")
return
}
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print(responseString!)
}
task.resume()
}
然后我称之为
var link = "link"
var passedPostString = "passedPostString"
print(post(link: link , passedPostString: passedPostString ))
将返回获取的值
答案 0 :(得分:1)
dataTask
方法是异步的,因此无法返回立即返回值,因为您不知道何时会调用它。
最好的办法是传入一个完成处理程序,该处理程序将从主代码中异步调用:
func post(link:String, passedPostString:String, completionHandler: @escaping (NSString) -> ()) {
let request = NSMutableURLRequest(url: NSURL(string: link)! as URL)
request.httpMethod = "POST"
request.httpBody = passedPostString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(String(describing: error))")
print("******Error*****")
return
}
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
completionHandler (responseString!);
}
task.resume()
}
var link = "link"
var passedPostString = "passedPostString"
let completion = { (result: NSString) in print(result) }
post(link: link, passedPostString: passedPostString, completionHandler: completion)
答案 1 :(得分:0)
进行异步网络调用的函数不能具有返回类型,因为在完成之前可能需要一段时间。你不希望系统冻结并等到响应,这将超过目的。
您可以添加一个带有完成闭包的新参数,当请求完成时将调用该完成闭包:
func post(link:String,passedPostString:String, completion: @escaping (String?, Error?) -> Void) {
let request = NSMutableURLRequest(url: NSURL(string: link)! as URL)
request.httpMethod = "POST"
request.httpBody = passedPostString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
// Make sure there is no error, else..
guard error == nil else {
completion(nil, error)
return
}
let responseString = String(data: data!, encoding: String.Encoding.utf8)
completion(responseString, nil)
}
task.resume()
}