MNM
MNM

Reputation: 2743

Perform some code before a segue after I push a button in swift

I have a button that goes to another view. I want to perform some code before the segue moves. The problem I am facing is the segue goes to the other page before the code has a chance to finish. So the values that are in the User default don't get changed before the view gets changed. My question is how can I get the code to run and after its done get the segue to fire? Here is what I have so far:

 @IBAction func onLogoutClick(sender: AnyObject) {
    //clear all url chache 
    NSURLCache.sharedURLCache().removeAllCachedResponses()
    //null out everything for logout
    email = ""
    password = ""
    self.loginInformation.setObject(self.email, forKey: "email")
    self.loginInformation.setObject(self.password, forKey: "password")
    self.loginInformation.synchronize()
    //self.view = LoginView
}

Upvotes: 5

Views: 5304

Answers (3)

Sandip Patel - SM
Sandip Patel - SM

Reputation: 3394

For Swift 4:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "Segue identifier set in storyboard") {
            // Put your code here
        }
    }

Upvotes: 0

Paulw11
Paulw11

Reputation: 114773

You have a couple of options;

The first is to remove the action from the button in IB and then create a segue between the UIViewController object and your next scene;

@IBAction func onLogoutClick(sender: AnyObject) {
    //clear all url chache 
    NSURLCache.sharedURLCache().removeAllCachedResponses()
    //null out everything for logout
    email = ""
    password = ""
    self.loginInformation.setObject(self.email, forKey: "email")
    self.loginInformation.setObject(self.password, forKey: "password")
    self.loginInformation.synchronize()

    self.performSegueWithIdentifier("logoutSegue",sender: self)
}

or you can get rid of the @IBAction method and implement prepareForSegueWithIdentifier

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
   if segue.identifier == "logoutSegue"  {
        //clear all url chache 
        NSURLCache.sharedURLCache().removeAllCachedResponses()
        //null out everything for logout
        email = ""
        password = ""
        self.loginInformation.setObject(self.email, forKey: "email")
        self.loginInformation.setObject(self.password, forKey: "password")
        self.loginInformation.synchronize()
   }
}

Upvotes: 9

user212514
user212514

Reputation: 3130

In your view controller you can implement:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "Segue identifier set in storyboard") {
        // Put your code here or call onLogoutClick(null)
    }
}

Upvotes: 2

Related Questions