Answer the question
In order to leave comments, you need to log in
Variable change in URLSession SWIFT function?
Hello! Help, save! I'm recently learning swift. I want to transfer the data request from the server to a separate class as a function. I tried many different options before asking here, but userInfo still doesn't change in the block do {
userInfo["firstName"]= responseApi.user[0].first_name
userInfo["lastName"] = responseApi.user[ 0].last_name
}
Please tell me how to do it right, if it's real at all.
var userInfo = [String:String?]
func getInfoUser (id_users: String) -> [String: String?] {
/*GET INFO USER*/
guard let url = URL(string: Shared.apiUrl + "users/user.php") else { return userInfo}
let postString = "id_users=" + id_users
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = postString.data(using: .utf8)
URLSession.shared.dataTask(with: request) {(data, response, error) in
guard let data = data else {return}
struct responseApi : Decodable {
var error: errorApi?
var response: String?
var user: [userApi]
}
struct errorApi: Decodable {
var error_code: String
var error_msg: String
}
struct userApi: Decodable {
//var : String
}
do {
let responseApi = try JSONDecoder().decode(responseApi.self, from: data)
/*CHECK API ERRORS*/
if responseApi.error != nil{
let error = responseApi.error?.error_code
let error_msg = FuncClass().iserror(error_code: error!)
}
/*END CHECK API ERRORS*/
userInfo["firstName"]= responseApi.user[0].first_name
userInfo["lastName"] = responseApi.user[0].last_name
}
catch let error {
print("ERROR CATCH")
print(error)
return
}
}.resume()
/*END GET INFO USER*/
return userInfo
}
Answer the question
In order to leave comments, you need to log in
Here's the story... URLSession.shared.dataTask...resume() is an asynchronous call, it is executed after getInfoUser exits: (we haven't touched the structures that copy yet). You need to do something like this:
and then:
var userInfo: [String:String?] = [:]
userInfo["firstName"]= responseApi.user[0].first_name
userInfo["lastName"] = responseApi.user[0].last_name
comepletion(userInfo)
getInfoUser(id_users: "", completion: {
~code here~
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question