Coder221 Coder221 - 1 month ago 12
Swift Question

Thread1:EXC_BAD_ACCESS(code=1, address = 0X48) when button is pressed

var buttonTapPlayer = AVAudioPlayer()


override func viewDidLoad() {
super.viewDidLoad()

DispatchQueue.global(qos: .background).async {
do{
let correctSoundUrl: URL = URL(fileURLWithPath: Bundle.main.path(forResource: "buttonTap", ofType: "wav")!)
self.buttonTapPlayer = try AVAudioPlayer(contentsOf: correctSoundUrl)
self.buttonTapPlayer.prepareToPlay()
}
catch{}
}
}


@IBAction func buttonPressed(_ sender: UIButton) {

self.buttonTapPlayer.play()
performSegue(withIdentifier: "showDetail", sender: sender)

}


I have the above code in my swift project. My project crashes the very first time I run the project in simulator at
self.buttonTapPlayer.play()

with the following error:


Thread1:EXC_BAD_ACCESS(code=1, address = 0X48)


However, when I re-run it, everything is fine. How do I resolve this?

Answer

You can't do it. You've build your buttonTapPlayer in a background thread and you try to call it from the main thread (to IBAction method). The compiler crashed to play() because your player is not yet ready.

To avoid this, you could build your player inside:

DispatchQueue.main.async {
   // build your stuff to the main thread
}

or simply remove DispatchQueue.global(qos: .background).async {}