Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift ERROR : : Call can throw, but it is not marked with 'try' and the error is not handled [duplicate]

I just started to learning Swift and,I'm trying to add a song into my code to play it when i press the button but that error shows up. how to fix this error?

var buttonAudioPlayer = AVAudioPlayer()

@IBAction func btnWarning(sender: UIButton) {
    play()
}

override func viewDidLoad() {
    super.viewDidLoad()
}

func play() {
    let buttonAudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("warning", ofType: "mp3")!)
    let one = 1

    if one == 1 {
        buttonAudioPlayer = AVAudioPlayer(contentsOfURL: buttonAudioURL) //getting the error in this line
        buttonAudioPlayer.prepareToPlay()
        buttonAudioPlayer.play()
    }
}
like image 318
CemAtes Avatar asked Dec 14 '22 09:12

CemAtes


1 Answers

The compiler correctly tells you that the initializer can throw an error as the method declaration correctly states (e.g. when the NSURL does not exist):

init(contentsOfURL url: NSURL) throws

Therefore you as the developer have to handle an eventually occuring error:

do {
    let buttonAudioPlayer = try AVAudioPlayer(contentsOfURL: buttonAudioURL)
} catch let error {
    print("error occured \(error)")
}

Alternatively you can tell the compiler that the call will actually always succeed via

let buttonAudioPlayer = try! AVAudioPlayer(contentsOfURL: buttonAudioURL)

But that will cause your app to crash if the creation actually does not succeed - be careful. You only should use the second approach if you are trying to load app resources that have to be there.

like image 56
luk2302 Avatar answered Dec 22 '22 01:12

luk2302