我在我的应用程序中制作了一项功能,可让您将音乐静音,我在此处放置了一个开关,以便您可以在打开和关闭之间进行切换。但是,该开关在应用程序中工作正常,当我关闭 vie 控制器并将其拉回时,它仍会显示它是如何离开的,但是当您关闭应用程序并重新打开它时,开关看起来好像它关闭了但它仍然播放音乐。这是我的代码,我会附上一张图片。
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.
}
}