我有一个简单的功能,只有一个例外。
static func configSessionAndSend(request: URLRequest) -> Character {
// Create and run a URLSession data task with our JSON encoded POST request
var responseChar: Character = "1"
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request) { (responseData, response, responseError) in
guard responseError == nil else {
//TODO: error handling
return
}
// APIs usually respond with the data you just sent in your POST request
if let data = responseData, let utf8Representation = String(data: data, encoding: .utf8), let httpUrlResponse = response as? HTTPURLResponse {
responseChar = StringHelper.getSecondLetter(stringValue: utf8Representation)
print("response: ", utf8Representation) //print server response
//print(httpUrlResponse.allHeaderFields) //print server headers
print("server response status: ", httpUrlResponse.statusCode) //print status code; use this later to check if 200 all OK
print("server respose char: ", responseChar)
} else {
print("no readable data received in response")
}
}
task.resume()
return responseChar
}
我的服务器应该返回0,并且我修改了变量responseChar,print("server respose char: ", responseChar)
在if语句内部时给出了正确的值。但是return responseChar
返回1,就像我的初始变量从未被修改过一样?我做错了什么?