Coder221 Coder221 - 2 years ago 259
Swift Question

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

var buttonTapPlayer = AVAudioPlayer()

override func viewDidLoad() {
super.viewDidLoad() .background).async {
let correctSoundUrl: URL = URL(fileURLWithPath: Bundle.main.path(forResource: "buttonTap", ofType: "wav")!)
self.buttonTapPlayer = try AVAudioPlayer(contentsOf: correctSoundUrl)

@IBAction func buttonPressed(_ sender: UIButton) {
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

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 Source

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 .background).async {}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download