Search code examples
iosswiftnsuserdefaultsuserdefaults

Saving data with User defaults


I am making a feature in my app that allows you to mute the music, i put a switch there so you can change it between on and off. However, the switch works fine in the app, when i close the vie controller and i pull it back up it will still show it how it was left, but when you close the app and open it back up the switch looks as if it off but it still plays the music.This is my code and i will attach a picture.

import Foundation
import UIKit
import SpriteKit
import AVFoundation




var bombSoundEffect: AVAudioPlayer!
var Ghost = SKSpriteNode()

class SecondViewController: UIViewController {

var sw = false




@IBOutlet var mySwitch: UISwitch!

@IBAction func switchpressed(_ sender: AnyObject) {

let defaults = UserDefaults.standard

    if mySwitch.isOn{
                defaults.set(true, forKey: "SwitchState")

        if bombSoundEffect != nil {
            bombSoundEffect.stop()
            bombSoundEffect = nil

        }

    }
    else{
        defaults.set(false, forKey: "SwitchState")

        let path = Bundle.main.path(forResource: "newmusic.wav", ofType:nil)!
        let url = URL(fileURLWithPath: path)


        do {
            let sound = try AVAudioPlayer(contentsOf: url)
            bombSoundEffect = sound
            sound.numberOfLoops = -1
            sound.play()
        } catch {
            // couldn't load file :(
        }

    }


}


override func viewDidLoad() {
    super.viewDidLoad()

    super.viewDidLoad()

    let defaults = UserDefaults.standard

    if (defaults.object(forKey: "SwitchState") != nil) {
        mySwitch.isOn = defaults.bool(forKey: "SwitchState")


    }
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Release any cached data, images, etc that aren't in use.
}


}

and here is the picture enter image description here If you didn't understand what i said above please ask questions.


Solution

  • As i understand from your code, you are not checking the User Defaults properly. In your viewDidLoad you have to check the bool value of your user defaults is set to true or not.

    override func viewDidLoad() {
        super.viewDidLoad()
        let defaults = UserDefaults.standard
    
        //check bool Value is set to true or not
    
        if defaults.bool(forKey: "SwitchState") == true {
            mySwitch.isOn = defaults.bool(forKey: "SwitchState")
    
        } else {
           print("false")
    
        }
    }
    

    Please check this code. Hopefully it will helps you.