1

here is my code (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.
   }
}

this is the method I found on my "Documentation and API References" to play audio: ``

initWithContentsOfURL:error:
init(contentsOfURL url: NSURL) throws

So, I return a String as source path, then conver it to NSURL. Now i want to play the audio but the method I am using needs to throw the error and handle it. How should I throw and handle the error ?

2 Answers 2

3

Swift 2.0

AVAudioPlayer will throw an exception if its initializer fails. Catch the error by wrapping its initialization in a do/catch clause.

do {
    let audioPlayer = try AVAudioPlayer(contentsOfURL: filePathUrl)
    // use audioPlayer
} catch {
    // handle error
}

As you can see, the keyword try is inserted before any method call that can throw exceptions. As long as the try statement doesn't throw, you can continue your code as normal. If the try statement does throw, you program will jump to the catch clause.

Examining the error

If you'd like to examine the error, you can convert it to an NSError by writing your catch statement like so (as seen in 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
}

Converting to NSError is only necessary if you want to examine an error thrown by one of Apple's Cocoa objects. Native Swift code, throwing native ErrorType errors, require no conversion.

I recommend you read Apple's new docs on error handling in Swift.


Swift 1.2

If you are using Swift 1.2, then there is no error handling available. Instead, AVAudioPlayer's initialization method will fail and return nil.

If you are using Swift 1.2, I would recommend initializing the audio player like this:

var initError: NSError?
if let audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: &initError) {
    // use audioPlayer
} else {
    println(initError) // handle error
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way to actually catch what the error is in Swift 2?
@devios Yes. Check out Error Handling in Apple's Interop Docs if you are working with one of Apple's APIs, which shows how to convert the thrown exception into an NSError. Or the Swift docs if your own Swift code will be throwing errors, in which case NSError is not needed
0

Since Swift 1.2, you cannot throw/handle exceptions. While it is available in swift2 (need XCode7 support) which is still in beta. See this article for detail (https://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.