【发布时间】:2014-11-22 05:22:03
【问题描述】:
我在 iPhone 模拟器中使用 “摇动手势” 时不断收到以下错误:
致命错误:在展开可选值时意外发现 nil
这是我的相关代码:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var soundFiles = ["kidLaughing", "pewpew", "pingas", "runningfeet"]
var player: AVAudioPlayer = AVAudioPlayer()
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
if event.subtype == .MotionShake {
var randomSoundFile = Int(arc4random_uniform(UInt32(soundFiles.count)))
var fileLocation = NSString(string:NSBundle.mainBundle().pathForResource("sounds/" + soundFiles[randomSoundFile], ofType: "mp3")!)
var error: NSError? = nil
player = AVAudioPlayer(contentsOfURL: NSURL(string: fileLocation), error: &error)
player.play()
}
}
}
我有一个名为 sounds 的文件夹,其中包含 4 个 mp3 文件。错误发生在这行代码上:
var fileLocation = NSString(string:NSBundle.mainBundle().pathForResource("sounds/" + soundFiles[randomSoundFile], ofType: "mp3")!)
我已经尝试了所有我能想到的方法来让它发挥作用,但我所尝试的一切都没有奏效。任何帮助表示赞赏!
【问题讨论】:
标签: ios objective-c swift avaudioplayer nsbundle