I am building a streaming audio app using SoundCloud API. There are 4 view controllers and the 4th view controller is the now playing track VC - similar to the Now Playing scene on the Music app.
When the app is in the foreground, everything is fine and the next audio track starts playing correctly. When the the app moves to the background, the current track keeps playing but as soon as it ends, the next track does not play until I bring the app back into the foreground. I have checked a bunch of existing issues such as iOS background audio not playing but none of the suggested solutions work.
I've pasted below the code for the playTrack method which is used to play tracks. When I use the debugger I can see that if I add a breakpoint inside the closure below, the breakpoint is not triggered until the app enters the foreground.
func playTrack(track: SongSearchResult) {
println("Playing track: \(track.title)")
Logging.sharedInstance.writeData(String(format: "%@:Playing track(%@)", __FUNCTION__, track.title))
audioPlayer?.stop()
if playPauseButton.enabled == false {
if let request: AnyObject = currentGetRequest {
SCRequest.cancelRequest(request)
}
}
currentGetRequest = SCRequest.performMethod(SCRequestMethodGET,
onResource: NSURL(string: track.streamURL),
usingParameters: nil,
withAccount: SCSoundCloud.account(),
sendingProgressHandler: nil,
responseHandler: {(response, data, error) in
dispatch_async(dispatch_get_main_queue()) {
var playerError: NSError? -----------------> BREAKPOINT SET HERE
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
self.audioPlayer = AVAudioPlayer(data: data, error: &playerError)
self.audioPlayer?.delegate = self
self.delegate?.currentTrackChanged(self)
self.audioPlayer?.prepareToPlay()
self.audioPlayer?.play()
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateTime:"), userInfo: nil, repeats: true)
self.playPauseButton.enabled = true
self.currentTimeSlider.enabled = true
}
})
}
I have already set the UIBackgroundModes 'audio' value in the Info.plist file. Does someone have any suggestions of what I'm doing wrong?
Thanks, Abhishek.