2

I had a Swift file that worked fine in Xcode6. When I upgraded to Xcode7, I now get an error that prevents the program from compiling. Below is the code snippet that is not working. The error that I receive just states "Could not find overload for 'PathForResource' that accepts the supplied arguments."

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()


}
Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
  • 1
    This is not an answer to your question, just a comment on the code you have provided: you really ought not to put the calls to `prepareToPlay()` and `play()` outside of the `do` block in the way you have done, because if creating the audio player fails it will try to play something non-existent. – TwoStraws Jul 06 '15 at 22:43
  • @TwoStraws so would you suggest wrapping the two calls in a conditional? the condition checks if the audioPlayer has a good value? – Dan Beaulieu Jul 06 '15 at 23:03
  • You ought to consider moving `prepareToPlay()` and `play()` directly beneath the `try` line. If the `try` fails execution will jump straight to the `catch` block so there's no risk of the following two lines being executed. – TwoStraws Jul 06 '15 at 23:06

1 Answers1

1

You have too many exclamation marks for Swift 2, because fileURLWithPath now returns NSURL not NSURL?.

Specifically, change this:

sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("red", ofType: "wav")!)!

To this:

sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("red", ofType: "wav")!)

…and the problem should go away.

TwoStraws
  • 12,862
  • 3
  • 57
  • 71