Oren Edrich Oren Edrich - 2 months ago 10
iOS Question

Userdefaults to save switch state

I Have a switch that when turned to "on" will put the music and when the switch is set to "off" the music will resume playing. My problem is that when i leave the view controller the switch will appear as "off" when it is switch "on". The code for my switch is below, I'm not sure what to write in order for the app to remember the switch state, please help.

//
// SecondViewController.swift
// Urban Sphere
//
// Created by Oren Edrich on 9/11/16.
// Copyright © 2016 Oren Edrich. All rights reserved.
//

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) {

if mySwitch.isOn{

if bombSoundEffect != nil {
bombSoundEffect.stop()
bombSoundEffect = nil
}
}
else{
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()

}

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

}

TDM TDM
Answer

I have a similar situation to yours, and I just use UserDefaults. Here's a step-by-step guide on how to do it.

  1. Create a variable like the following example. This will set the default setting and store the state of the check box for use later:

    var musicSetting = UserDefaults().string(forKey: "Music") ?? "On"
    
  2. In your viewDidLoad, add an if statement that will check whether the Check Box should be On or Off, like this:

    if musicSetting == "On" {
        theNameOfYourCheckbox.state = NSOffState
    } else {
        theNameOfYourCheckbox.state = NSOnState
    }
    
  3. In the IBAction property for your check box, add an if statement like the following that will save your Setting, depending on what it is:

    if theNameOfYourCheckbox.state == NSOnState {
        UserDefaults().set("On", forKey: "Music")
    } else {
        UserDefaults().set("Off", forKey: "Music")
    }