用swift读取UserDefault值

时间:2016-10-21 00:39:06

标签: swift nsuserdefaults

我正在尝试编写一个按钮,将UserDefault设置为true。当视图加载时,我希望它检查用户默认值是否为true。如果是的话,我希望它通过一行代码来完成。

这是我的代码:

import UIKit
import SpriteKit
import AVFoundation

var bombSoundEffect: AVAudioPlayer!
let instruct = UserDefaults.standard

class GameViewController: UIViewController {
    @IBOutlet weak var intructions: UIButton!
    @IBAction func intructions(_ sender: AnyObject) {
        instruct.set(true, forKey: "instructions")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if instruct.value(forKey: "instructions") {
            intructions.isHidden = true
        }

        let path = Bundle.main.path(forResource: "Untitled2.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 :(
        }

        if let scene = GameScene(fileNamed:"GameScene") {
            // Configure the view.
            let skView = self.view as! SKView
            skView.showsFPS = false
            skView.showsNodeCount = false

            /* Sprite Kit applies additional optimizations to improve rendering performance */
            skView.ignoresSiblingOrder = true

            /* Set the scale mode to scale to fit the window */
            scene.scaleMode = .aspectFill
            scene.size = self.view.bounds.size

            skView.presentScene(scene)
        }
    }

1 个答案:

答案 0 :(得分:1)

更改

if instruct.value(forKey: "instructions")

if instruct.bool(forKey: "instructions")