Search code examples
iosswiftdelegatesavaudioplayer

Cannot setup AVAudioPlayerDelegate in a Manager class


I am using a manager class that I initialize as a global variable in my AppDelegate.swift class to manage playing the music in my App. Here's some of the code for my Manager class

import Foundation
import AVFoundation
import MediaPlayer

/*
protocol PlayerDelegate : class {
    func soundFinished(sender : AnyObject)
}*/
var quoteList = [Quote]()
var isRandomQuote = false

enum alarmTypes {
case song
case quote
case randomQuote
}
var myAVAudioPlayer:AVAudioPlayer = AVAudioPlayer()
var MPMediaPlayer = MPMusicPlayerController()

public class MediaManager: NSObject, AVAudioPlayerDelegate{

//weak var delegate : PlayerDelegate?

var MPMediaItem: MPMediaItemCollection!
var quoteSelected = Quote()

var alarmType = alarmTypes.randomQuote

func selectRandom(){
    self.alarmType = alarmTypes.randomQuote
    quoteSelected = pickRandomQuote()
}
func selectSong(MPMedia: MPMediaItemCollection){
    self.alarmType = alarmTypes.song
    MPMediaItem = MPMedia
}
func selectQuote(quote: Quote){
    self.alarmType = alarmTypes.quote
    quoteSelected = quote
}



var isPlaying:Bool = false

  override init(){
    super.init()
  myAVAudioManager.delegate = self 
}

However when I go to run the code I get this error: Thread 1: EXC_BAD_ACCESS(Code = 1, address = 0x8)

I have tried making other files the delegate but that has also not worked. Is there any way to make my manager the delegate so that it can respond to the player when it finishes playing a song?


Solution

  • I think the myAVAudioManager is still nil when you set delegate. Try to create new instance of AVAudioPlayer before.