我需要在另一个 View Controller 中使用输出数据,但我不能使用,该字符串仅返回一个空字符串:
func callApi(postString: String) -> (String) {
var outputdata = String()
var req = LogIn(postString: postString)
let task = URLSession.shared.dataTask(with: req) { (data, response, error) in
if let data = data{
outputdata = String(data: data, encoding: String.Encoding.utf8)!
//print(outputdata)
}
}
print(outputdata)
return (outputdata)
}
最佳答案
您可以尝试这个,因为该过程是异步的
func callApi(_ postString: String,completion:@escaping:(_ res:String?) -> Void ) {
var req = LogIn(postString: postString)
URLSession.shared.dataTask(with: req) { (data, response, error) in
if let data = data{
completion(String(data: data, encoding: String.Encoding.utf8))
}
else {
completion(nil)
}
}.resume()
}
通话
callApi("SendedValue") { res in
print(res)
}
关于ios - 我如何将数据传递给 swift4 中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52355795/