N
N
nastya_zholudeva2018-06-11 20:31:11
Swift
nastya_zholudeva, 2018-06-11 20:31:11

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.
For the task of transferring data to the next page, I use prepare for segueit 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

1 answer(s)
D
doublench21, 2018-06-11
@nastya_zholudeva

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 method
self.performSegue(withIdentifier: "sucsessLoginSegue", sender: self)
and already use the result of the call in
prepare(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 question

Ask a Question

731 491 924 answers to any question