Error called trying to get Bundle URL

2020-05-06 13:06发布

问题:

I am getting an error when I try to get a path of an audio file I have.

let path = Bundle.main.path(forResource: "SaveALife", ofType: "mp3")!

In the console I receive this:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Any help? Thanks.

回答1:

Make sure SaveALife.mp3 should be in your bundle. Also when you drag and drop the file please check copy bundle resources.



回答2:

I will go with @Rob, You must have spelled the resource name incorrectly or the file is not there in the bundle. And by providing "!" you are forcing to get string path, but as the file is not there Or due to spelling mismatch the file is not found in bundle, the return path would be nil, and due to "!" it tries to unwrap the nil which results the crash.

So the solution is remove the "!" like below

let path = Bundle.main.path(forResource: "SaveALife", ofType: "mp3")

Or else if you definitely want to use "!", You must have to give correct resource path and confirm that the resource must be there in the bundle.

Hope it helps.

Happy coding ...