【发布时间】:2015-07-06 22:33:50
【问题描述】:
我有一个在 Xcode6 中运行良好的 Swift 文件。当我升级到 Xcode7 时,我现在收到一个阻止程序编译的错误。下面是不起作用的代码 sn-p。我收到的错误只是指出“找不到接受提供的参数的 'PathForResource' 的重载。”
func playRecord(sender:UITapGestureRecognizer){
var tag = sender.view!.tag
let sound:NSURL
switch tag{
case 0: // red
sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("red", ofType: "wav")!)!
case 1: // blue
sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("blue", ofType: "wav")!)!
case 2: // white
sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("white", ofType: "wav")!)!
default:
sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("red", ofType: "wav")!)!
}
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: sound)
} catch _ {
audioPlayer = nil
}
audioPlayer.prepareToPlay()
audioPlayer.play()
}
【问题讨论】:
-
这不是对您问题的回答,只是对您提供的代码的评论:您真的不应该在
do块之外调用prepareToPlay()和play()以您所做的方式,因为如果创建音频播放器失败,它将尝试播放不存在的东西。 -
@TwoStraws 那么您是否建议将这两个调用包装在一个条件中?条件检查 audioPlayer 是否具有良好的价值?
-
您应该考虑将
prepareToPlay()和play()直接移动到try行的下方。如果try执行失败,将直接跳转到catch块,因此不存在执行以下两行的风险。