Post

Replies

Boosts

Views

Activity

Optional somehow becomes nil after passing through a condition to prevent that
I am working on an audiobook app and ran into this issue. I created a simplified version of the app to help localize the problem I am having initializing an AVAudioPlayer object from AVKit. .onAppear(perform: { let song = Bundle.main.url(forResource: "01", withExtension: "mp3") if song != nil { self.player = try! AVAudioPlayer(contentsOf: song!) } Within an .onAppear tag I created a url object that connects to the mp3 file I wish to play. The app then passes that url into a conditional statement making sure it is not nil. It then loads the mp3 into the AVAudioPlayer object. As soon as the app leaves the .onAppear tag however, it crashes at line 34 do to unwrapping a nil optional. Here is a link to the full simplified project: https://github.com/myk410/AudioText/blob/4cbc2773cff657b73df0eef8ffec84dc7a463749/AudioText/ChapterDetailView.swift Using a do{} catch{} instead of force unwrap to load the AVAudioPlayer delivers the same results: .onAppear(perform: {             let song = Bundle.main.url(forResource: "01", withExtension: "mp3")             if song != nil {                 do{                     self.player = try AVAudioPlayer(contentsOf: song!)                 }                 catch{                     print(error)                 }             }         })
2
0
435
Dec ’21