swift - Why do I keep getting this error??? fatal error: unexpectedly found nil while unwrapping an Optional value -


i trying create app sound built in. whenever try build program error:

fatal error: unexpectedly found nil while unwrapping optional value

here code:

var magicsound: avaudioplayer = avaudioplayer()  @iboutlet var answer: uilabel!  var answerarray = ["yes", "no", "maybe", "try again", "not now", "no doubt", "yes indeed", "of course", "definetley not"] var chosenanswer = 0  override func viewdidload() {     super.viewdidload()      let magicfile = bundle.main.path(forresource: "magicsound", oftype: ".wav")      {         try magicsound = avaudioplayer(contentsof: url (fileurlwithpath: magicfile!))     }     catch {         print(error)     } }  override func motionended(_ motion: uieventsubtype, event: uievent?) {     if event?.subtype == motion {         printanswer()         randomanswer()         animation()         showingansweranimation()         magicsound.play()     } } 

the console throws error @ line,

try magicsound = avaudioplayer(contentsof: url (fileurlwithpath: magicfile!)) 

if me fix code great.

i believe line:

let magicfile = bundle.main.path(forresource: "magicsound", oftype: ".wav") 

should be:

let magicfile = bundle.main.path(forresource: "magicsound", oftype: "wav") 

the dot character implicit in type parameter. how write it:

if let magicfile = bundle.main.path(forresource: "magicsound", oftype: "wav") {     let magicsound = try? avaudioplayer(contentsof: url (fileurlwithpath: magicfile)) } else {     print( "magicsound.wav not exist in main bundle" ) } 

make sure file name exact case-sensitive match.also make sure resource file @ top level of bundle (i.e. in same folder .xcodeproj , .xcworkspace file).


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -