Answer the question
In order to leave comments, you need to log in
Why doesn't the API request work inside the prepare for segue method?
I am making an authorization page and it is necessary that after the user has successfully logged in, there is a transition to the next page. In this case, there must also be a request, the data from the response of which must be transferred to this next page. I am trying to implement it like this.
On LoginViewController I make a registration request, on success I call
self.performSegue(withIdentifier: "sucsessLoginSegue", sender: self)
to go to the next page and by clicking on the button "Register" I call this function. prepare for segue
it inside which I make a request to obtain the data that needs to be transferred. However, print("1111111")
inside this method it works, but print("items111:", items)
no longer. What am I doing wrong?func register() {
let api = JsonPlaceholder()
api.post(uri: "users/", params: ["username" : login.text!, "email" : email.text!, "password" : password.text!], callback: { (items) in
print("items login: ", items)
self.performSegue(withIdentifier: "sucsessLoginSegue", sender: self)
})
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let ParentVC = segue.destination as! ParentViewController
print("1111111")
let api = JsonPlaceholder()
api.get(uri: "tabs/", params: [:], callback: { (items) in
print("items111:", items)
var menuItems = [String]()
for menuItem in items {
menuItems.append(menuItem.1["name"].stringValue)
}
ParentVC.menuItems = menuItems
})
@IBAction func clickOnRegister(_ sender: UIButton) {
print("click!")
self.register()
}
}
Answer the question
In order to leave comments, you need to log in
Well, because you forget again that this is an Asynchronous method. When this method fires, the function
prepare(for segue: UIStoryboardSegue, sender: Any?)
already completes its work. There are two options. Make a request before calling a methodself.performSegue(withIdentifier: "sucsessLoginSegue", sender: self)
and already use the result of the call inprepare(for segue: UIStoryboardSegue, sender: Any?)
. Or make a request after the transition to a new VC.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question