I just began learning Swift, I am working with an API behind, the problem is that : Swift don't wait my function finish therefore my last function appears like no code was done before .
import Foundation
import UIKit
import Alamofire
import SwiftyJSON
// Classes
class User {
init(data: Any) {
self.sex = JSON(data)["sex"].string!
print(self.sex)
}
var id: Int = 1
var online: Bool = false
var picture: String = ""
var sex: String = "Male"
}
// Fonctions
func getBackground(_ apiURL: String, completion : @escaping(_ :Any) -> Void) {
// Requête API avec Alamofire + SwiftyJSON
AF.request(apiURL, method: .get).validate().responseJSON { response in
switch response.result {
case .success(let value):
let jsonData = JSON(value)
completion(jsonData["results"])
case .failure(let error):
print(error)
}
}
}
// Requête de connexion
getBackground("https://x..me", completion: { response in
let user = User(data: response)
})
print(String(user.id) + ": " + String(user.online!))
I have this error: "Use of unresolved identifier 'user'", I guess that Swift don't get the fact that User was defined previously
All my work works perfectly with my API, the "self.sex" is set and showed when I build the code. But I'm still "locked" like I can't do nothing after this code because Swift don't want to wait.
I tried the function async and sync but then, all my next code has to be under a function...
Thanks in advance
There's no need to wait.
Put the print
line – and the code which proceeds the user – in the completion closure
getBackground("https://a.clet.me", completion: { response in
let user = User(data: response)
print(String(user.id) + ": " + String(user.online!))
})
The error Use of unresolved identifier 'user'
occurs because the local variable user
is only visible inside the scope ( {}
) of its declaration.
So, this problem is all about variables life cycle.
// This happens first
getBackground("https://a.clet.me", completion: { response in
let user = User(data: response)
// This happens third, once the request has completed.
// user exists here.
// Only after this moment you should handle anything related to the user
})
// This happens second
// user DOESN'T exist here, swift will move on
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.