【发布时间】:2017-12-16 16:00:16
【问题描述】:
我正在开发一个应用程序,它会在设备抖动时播放一首随机歌曲。以下是我的代码
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if event?.subtype == UIEventSubtype.motionShake{
let soundArray=["firstsong","second","fourth"]
let randomNumber=Int(arc4random_uniform(UInt32(Int32(soundArray.count))))
let fileLocation = Bundle.main.path(forResource: soundArray[randomNumber], ofType: "mp3")
do {
try player=AVAudioPlayer(contentsOf:URL(fileURLWithPath:fileLocation!))
player.play()
}catch{
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我已将我的 mp3 文件放在音乐文件夹中。 当我摇动设备时,我收到以下错误
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
任何帮助将不胜感激
【问题讨论】:
-
好的,你需要调试你的代码。用局部变量把它分成小步骤,在函数的顶部设置一个断点,然后单步执行,检查每一行的结果。我的钱在
fileLocation!这个表达式上。如果 fileLocation 为 nil,则会崩溃。 (我将 force-unwrap 运算符称为“crash if nil”运算符。在您真正知道自己在做什么之前,您应该避免使用它。)