我正在开发一个能够在后台播放音乐的音乐播放器应用程序。只要音乐正在播放,应用程序就不会被终止,但如果播放停止并且应用程序处于后台,它可能会被终止。为了让应用程序对用户更加友好,我想在应用程序被系统终止时保存播放队列和状态,因此我在应用程序委托中实现了以下几行:
- (BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder
{
/*
Archive the current queue controller to be able to continue the playback like the app never has been terminated
when user is launching it again.
*/
SMKQueueController *queueController = [[UIApplication sharedApplication] queueController];
[coder encodeObject:queueController forKey:@"queueController"];
return YES;
}
- (BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder
{
/*
Restore the recently used queue controller to be able to continue the playback like the app never has been
terminated when use is launching it again.
*/
SMKQueueController *queueController = [coder decodeObjectForKey:@"queueController"];
[[UIApplication sharedApplication] setQueueController:queueController];
return YES;
}
有时(尤其是当我通过双击主页按钮菜单手动杀死它时)它会像我预期的那样工作。但有时,当应用程序被终止时,不会调用此方法。
所以我的问题是:我是否误解了这些方法的工作原理或它们的用途?或者有没有更好的地方来实现这样的功能?