NSBundle error Xcode 8

451 views Asked by At

I am following a beginner game tutorial online and I got to this point where I am linking a sound file to several buttons.

Here is the code for it:

let soundFilePath = NSBundle.mainBundle().pathForResource("1", ofType: "wav")
let soundFileURL = NSURL(fileIRLWithPath: soundFilePath!)

Unfortunately, "NSBundle" is highlighted red and it says "Replace NSBundle with Bundle". I did but then I get the "mainBundle" error and so on.

The tutorial I am following is using Xcode 7.3+ I am Using Xcode 8+ so I'm certain that's the problem. Is there a way I can rewrite the code so it works properly?

Thanks.

2

There are 2 answers

3
nbloqs On BEST ANSWER

In Swift 3, try this:

let soundFilePath = Bundle.main.path(forResource: "1", ofType: "wav")
1
vadian On

In Swift 3 many Foundation classes have been turned into native Swift structs (missing NS prefix). The benefit is dramatically reduced code and better conformance to the Swift value type semantics.

As you need an URL anyway use the URL related API of Bundle

let soundFileURL = Bundle.main.url(forResource:"1", withExtension: "wav")

Unfortunately only a few writers of online tutorials seem to know that :-/