Khoury
Khoury

Reputation: 431

Why does my User Defaults bool not set on first launch of app?

I have a UserDefault Bool for music playing.

When launched for the first time, I attempt to set the bool to true, like this...

if launchedBefore {

        // Do nothing.

    } else {

        UserDefaults.standard.set(true, forKey: "musicOn")
        print("music is \(musicOn)")
        UserDefaults.standard.set(true, forKey: "alreadylaunched")

    }

This is in viewDidAppear().

The problem is that it does not set as true on the first launch, regardless of where I set the bool, it could be without the launchedBefore check, it still does not set on the first time.

I don't see why this wouldn't work? musicOn is equal to false always on first launch, then on second launch, it is true?

Any insight would be appreciated. Thanks!

Upvotes: 0

Views: 861

Answers (2)

iOS Geek
iOS Geek

Reputation: 4855

You should use the method like this

let launchedBefore = UserDefaults.standard.bool(forKey: "alreadylaunched")
        if launchedBefore {

        // Do nothing.

    } else {

        UserDefaults.standard.set(true, forKey: "musicOn")
     //   print("music is \(musicOn)")
        UserDefaults.standard.set(true, forKey: "alreadylaunched")

    }

Upvotes: 1

Khoury
Khoury

Reputation: 431

What worked for me is allowing var musicOn to equal to user default bool once again.

if launchedBefore {

        // Do nothing.

    } else {

        UserDefaults.standard.set(true, forKey: "musicon")
        print("music is \(UserDefaults.standard.bool(forKey: "musicon"))")

        musicOn = UserDefaults.standard.bool(forKey: "musicon") // Stating it again works to update the bool.

        UserDefaults.standard.set(true, forKey: "alreadylaunched")

    }

Var musicOn was already instantiated outside of any functions, it seems it just needs to be set again.

Thanks you for your comments!

Upvotes: 1

Related Questions