简体   繁体   English

保存开关状态的用户默认值

[英]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.
}

}

I found the correct answer and decided to post it incase anyone has the same question.我找到了正确的答案并决定发布它以防万一有人有同样的问题。

@IBAction func saveSwitchState(sender: AnyObject) {
    var defaults = NSUserDefaults.standardUserDefaults()

if bluetoothSwitch.on {
    defaults.setBool(true, forKey: "SwitchState")
} else {
    defaults.setBool(false, forKey: "SwitchState")
}
}

and...和...

override func viewDidLoad() {
super.viewDidLoad()

var defaults = NSUserDefaults.standardUserDefaults()

if (defaults.objectForKey("SwitchState") != nil) {
    bluetoothSwitch.on = defaults.boolForKey("SwitchState")
}
}

You want know where to insert the code , I guess.你想知道在哪里插入代码,我猜。


updata更新数据


updata2 Then you can run directly. updata2 然后就可以直接运行了。 If it's useful , please UP this answer.如果有用,请UP这个答案。

import Foundation
import UIKit
import SpriteKit
import AVFoundation


class SecondViewController: UIViewController {

        static let bombSoundEffect = {()->(AVAudioPlayer) in

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

        var sw = false

        var Ghost = SKSpriteNode()


        @IBOutlet var mySwitch: UISwitch!

        @IBAction func switchpressed() {

            if mySwitch.isOn{

                SecondViewController.bombSoundEffect.play()
            }else{

                SecondViewController.bombSoundEffect.stop()
            }

            //*************    save status    *************
            UserDefaults.standard.set(mySwitch.isOn, forKey: "SwitchStatus");


        }

        override func viewDidLoad() {

            super.viewDidLoad()



            mySwitch.addTarget(self, action: #selector(switchpressed), for: .valueChanged)

            //*************    load status    *************
            mySwitch.isOn = UserDefaults.standard.bool(forKey: "SwitchStatus");
            switchpressed()

        }



    }

I have a similar situation to yours, and I just use UserDefaults.我和你有类似的情况,我只是使用 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:在您的viewDidLoad ,添加一个 if 语句,该语句将检查复选框是否应为开或关,如下所示:

     if musicSetting == "On" { theNameOfYourSwitch.isOn = false } else { theNameOfYourSwitch.isOn = true }
  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:在复选框的IBAction属性中,添加如下 if 语句,该语句将保存您的设置,具体取决于它是什么:

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

Here's a screenshot that might help:这是一个可能有帮助的屏幕截图: 图片在这里...

If you want to save the state of Switch in user default, then can use the native method如果你想在用户默认保存 Switch 的状态,那么可以使用 native 方法

UserDefaults.standard.set(_ value: Bool, forKey defaultName: String)

Like this像这样

    UserDefaults.standard.set(mySwitch.isOn, forKey: "SwitchStatus");
    UserDefaults.standard.synchronize();

While fetching switch status just use在获取开关状态时只需使用

    let status = UserDefaults.standard.bool(forKey: "SwitchStatus");

UPDATE :更新 :

@IBAction func switchpressed(_ sender: AnyObject) {

UserDefaults.standard.set(mySwitch.isOn, forKey: "SwitchStatus");

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 :(
    }
}
}

Hope it helps希望能帮助到你

Happy coding ...快乐编码...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM