3

So I have 4 buttons on a View Controller which is the initial View Controller of the application.

Each button is "SHOW" segued to a different navigation controller (which is connected to a UITableView).

My goal is to somehow save which button was touched using NSUserDefaults and skip over the View Controller and go directly to the selected Navigation Controller, every time the app is opened! Is this possible?

I am writing this in Swift

This is my AppDelegate (warning on "var buttonSelected"):

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        var buttonSelected = NSUserDefaults.standardUserDefaults().integerForKey("buttonSelected")

        print("run")

        return true
    }
}

This is my View Controller for my 4 Buttons :

import UIKit

class NSUserDefault: UIViewController {

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {   

        var buttonSelected: Int = 0

        if (segue.identifier == "button1Segue") {

            buttonSelected = 1
        }

        else if (segue.identifier == "button2Segue") {

            buttonSelected = 2
        }

        else if (segue.identifier == "button3Segue"){
            buttonSelected = 3
        }

        else if (segue.identifier == "button4Segue") {
            buttonSelected = 4
        }

        NSUserDefaults.standardUserDefaults().setInteger(buttonSelected, forKey: "buttonSelected") // Save the selection in user defaults
        NSUserDefaults.standardUserDefaults().synchronize() // Save changes

        print("runs")

        if buttonSelected == 1 {
            let welcomeVC: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("ONW") as UIViewController
            self.parentViewController?.presentViewController(welcomeVC, animated: true, completion: nil)
        }

        if buttonSelected == 2 {
            let welcomeVC: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("OE") as UIViewController
            self.parentViewController?.presentViewController(welcomeVC, animated: true, completion: nil)
        }

        if buttonSelected == 3 {
            let welcomeVC: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("OS") as UIViewController
            self.parentViewController?.presentViewController(welcomeVC, animated: true, completion: nil)
        }

        if buttonSelected == 4 {
            let welcomeVC: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("ON") as UIViewController
            self.parentViewController?.presentViewController(welcomeVC, animated: true, completion: nil)
        }
    }
}
Shades
  • 5,568
  • 7
  • 30
  • 48
  • 1
    Take a look at this https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/ – Bobby W Mar 07 '16 at 18:27
  • In your AppDelegate, implement something like in the answer here: http://stackoverflow.com/questions/27208103/swift-detect-first-launch – Shades Mar 07 '16 at 21:46
  • Just ran it on my phone again and it still continues to launch the initial view controller... I'll upload the new code back into my question @Shades – Brandon Priest Mar 07 '16 at 22:04
  • See all of my updated code – Shades Mar 07 '16 at 22:06
  • Im getting an error at "if let buttonSelected = NSUserDefaults..." right under the func application! The error says "Initializer for conditional binding must have Optional Type, not Int"?? @Shades – Brandon Priest Mar 07 '16 at 22:26
  • Ok, I fixed it. Read this: http://stackoverflow.com/questions/32645517/how-to-deal-with-non-optional-values-in-nsuserdefaults-in-swift – Shades Mar 07 '16 at 22:42
  • I continue getting a "Thread 1: signal SIGABRT" in my app delegate across the top when I try to launch my app and I can't figure out what it is... if I delete the code in the App Delegate it runs perfectly fine but when I copy and past the code back in... It crashes @Shades – Brandon Priest Mar 07 '16 at 23:28
  • @BrandonPriest You gotta read where it's coming from and what the error is – Shades Mar 07 '16 at 23:30

2 Answers2

0

Yes, it is possible.

1) You already know which button is being pressed, so get that info. Do this in prepareForSegue() or in the button's IBAction, if it has one.

2) Save the value in user defaults

3) When your app launches, read the user defaults key and show the proper view controller.

Here's how you can save the info:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

        var buttonSelected: Int = 0

        if (segue.identifier == "button1Segue") {

            buttonSelected = 1
        }

        else if (segue.identifier == "button2Segue") {

            buttonSelected = 2
        }

        // Etc . . .

        NSUserDefaults.standardUserDefaults().setInteger(buttonSelected, forKey: "buttonSelected") // Write the selection in user defaults
        NSUserDefaults.standardUserDefaults().synchronize() // Save changes
    }

Here's a way to pick the path:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let buttonSelected = NSUserDefaults.standardUserDefaults().integerForKey("buttonSelected")

        if buttonSelected != 0 {

            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vcName = ""

            switch buttonSelected {
            case 1:
                vcName = "Button1Controller"
             case 2:
                // Etc
            }

            let vc = storyboard.instantiateViewControllerWithIdentifier(vcName) 
            self.window?.rootViewController?.presentViewController(vc, animated: true, completion: nil)
        }
        else {
        // The user default wasn't saved yet
        }
    return true
}
Shades
  • 5,568
  • 7
  • 30
  • 48
  • Where would you put the "save the info" code? AppDelegate or in the ViewController.swift? – Brandon Priest Mar 07 '16 at 19:54
  • The "save" code is that last line in prepareforsegue() where it saves the selection to the user defaults. I'll update the code – Shades Mar 07 '16 at 19:58
  • @BrandonPriest AppDelegate is a good spot before other viewcontrollers are shown – Shades Mar 07 '16 at 20:14
  • When picking the path does it matter if I am not using the segue directly to the view controller? Because I am running it through a Navigation Controller first – Brandon Priest Mar 07 '16 at 20:26
  • @BrandonPriest The key point is that you have the identifier set up. So even if you dragged from the button in Interface Builder and don't need the code at all to segue, having the identifier allows prepareforsegue() to detect which segue is going to happen – Shades Mar 07 '16 at 20:29
  • Alright I just added all of the code and I don't have any errors... but I ran the app on my phone and when I kill the application it still takes me back to the initial view controller? Is there a way to keep that from happening, I want it to be permanent – Brandon Priest Mar 07 '16 at 20:39
  • @BrandonPriest I added a line to the code. You need that line to save the changes you make to user defaults – Shades Mar 07 '16 at 20:58
  • I added that line of code but it still seems to be doing the exact same thing...? Am I missing something? – Brandon Priest Mar 07 '16 at 21:03
  • Did you set the segue identifiers? Add a print line inside the prepareforsegue() if statements to make sure they're being called – Shades Mar 07 '16 at 21:04
  • I added a print statement and double checked all of the segue identifiers, the print statement ran fine and all the segue identifiers are there... is it maybe my app delegate code line...? Because there is a warning around it – Brandon Priest Mar 07 '16 at 21:13
  • I added a print statement and it seems to work the way it should... I don't know what could be wrong... the warning says "Initialization of variable buttonSelected was never used; consider replacing with assignment to '_' or removing it" – Brandon Priest Mar 07 '16 at 21:22
  • yeah I keep looking over my code and I'm not sure why it isn't saving even after killing the app or re running it @Shades – Brandon Priest Mar 07 '16 at 21:31
0

I hope this will to you

@IBAction func saveButton(sender: UIButton)
{
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setBool(true, forKey: "button1")
    defaults.synchronize()
}

check for button will like this

 func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {

     let prefs = NSUserDefaults.standardUserDefaults()
     if let prefs.boolForKey("button1") == true {          
        // here code if button was clicked
     } else {         
        // here code if button was not clicked
     }

     return true
    }
typedef
  • 917
  • 5
  • 9
  • Where would I place the "check for button" code? Would that go in my AppDelegate.swift? – Brandon Priest Mar 07 '16 at 19:06
  • Will this be more of a permanent solution?? Im hoping that even when I kill the application... and load it back up again it will pass through the initial view controller and go straight to the TableViewController – Brandon Priest Mar 07 '16 at 20:50