I\'ve properly enabled background audio for my app (in the plist). Playing the next track after the current is complete using SPPlaybackManager in the background (when the phone
The solution is very simple but it took me a year to realize it. My old solution was to start a background task just before the previous track ended, and keep it running until the next track was playing. That was very error prone. Instead:
Keep track of your playing state (playing or paused). Whenever you transition into Playing, start a background task. Never stop it, unless you transition into Paused. Keep the state as Playing even between tracks. As long as you have the audio background mode in your info.plist and audio is playing, your background task will have an infinite timeout.
Some pseudo code:
@interface PlayController
@property BOOL playing;
- (void)playPlaylist:(SPPlaylist*)playlist startingAtRow:(int)row;
@end
@implementation PlayController
- (void)setPlaying:(BOOL)playing
{
if(playing == _playing) return;
_playing = playing;
UIApplication *app = [UIApplication sharedApplication];
if(playing)
self.playbackBackgroundTask = [app beginBackgroundTaskWithExpirationHandler:^ {
NSLog(@"Still playing music but background task expired! :(");
[app endBackgroundTask:self.playbackBackgroundTask];
self.playbackBackgroundTask = UIBackgroundTaskInvalid;
}];
else if(!playing && self.playbackBackgroundTask != UIBackgroundTaskInvalid)
[app endBackgroundTask:self.playbackBackgroundTask];
}
...
@end
Edit: Oh, and I finally blogged about it.
CocoaLibSpotify does a lot of work to start playing a track and will likely spawn new internal threads in the process. I doubt this is allowed in the audio style of backgrounding so you'll likely need to start a temporary background task to change tracks.