这是我的代码(Swift):
import UIKit
import AVFoundation
class PlaySoundViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if var filePath = NSBundle.mainBundle().pathForResource("movie_quote",ofType: "mp3"){
var filePathUrl = NSURL.fileURLWithPath(filePath)
AVAUdioPlayer audioPlayer = AVAudioPlayer(contentsOfURL:filePathUrl) throws
}
else{
print("filePath is empty")
}
}
@IBAction func playSlowAudio(sender: UIButton) {
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
这是我在“文档和 API 引用”中找到的播放音频的方法: ``
initWithContentsOfURL:error:
init(contentsOfURL url: NSURL) throws
因此,我返回一个字符串作为源路径,然后将其转换为 NSURL。现在我想播放音频,但我使用的方法需要抛出错误并进行处理。我应该如何抛出和处理错误?
最佳答案
swift 2.0
AVAudioPlayer
如果其初始化器失败,将抛出异常。通过将其初始化包装在 do
/catch
子句中来捕获错误。
do {
let audioPlayer = try AVAudioPlayer(contentsOfURL: filePathUrl)
// use audioPlayer
} catch {
// handle error
}
如您所见,关键字try
被插入到任何可以抛出异常的方法调用之前。只要 try
语句没有throw
,您就可以照常继续您的代码。如果 try
语句执行 throw
,您的程序将跳转到 catch
子句。
检查错误
如果你想检查错误,你可以通过编写你的 catch
语句将它转换为 NSError
(如 Apple's Objective-C/Swift Interoperability Docs 所示):
do {
let audioPlayer = try AVAudioPlayer(contentsOfURL: filePathUrl)
// use audioPlayer
} catch let error as NSError {
// error is now an NSError instance; do what you will
}
转换为 NSError
仅当您想要检查由 Apple 的 Cocoa 对象之一抛出的错误时才有必要。 native Swift 代码,抛出 native ErrorType
错误,不需要转换。
我建议您阅读 Apple 的 new docs on error handling in Swift .
swift 1.2
如果您使用的是 Swift 1.2,则没有可用的错误处理。相反,AVAudioPlayer
的初始化方法将失败并返回 nil
。
如果您使用的是 Swift 1.2,我建议您像这样初始化音频播放器:
var initError: NSError?
if let audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: &initError) {
// use audioPlayer
} else {
println(initError) // handle error
}
关于swift - 如何快速抛出和处理错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31374905/