3

我正在开发一个能够在后台播放音乐的音乐播放器应用程序。只要音乐正在播放,应用程序就不会被终止,但如果播放停止并且应用程序处于后台,它可能会被终止。为了让应用程序对用户更加友好,我想在应用程序被系统终止时保存播放队列和状态,因此我在应用程序委托中实现了以下几行:

- (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;
}

有时(尤其是当我通过双击主页按钮菜单手动杀死它时)它会像我预期的那样工作。但有时,当应用程序被终止时,不会调用此方法。

所以我的问题是:我是否误解了这些方法的工作原理或它们的用途?或者有没有更好的地方来实现这样的功能?

4

1 回答 1

2

我参加了一个 WWDC 2012 会议,确切地描述了应该如何做。如果您是注册的 Apple 开发人员,则可以访问会议中的视频。这篇文章的标题是“在 iOS 上保存和恢复应用程序状态”。我发现这是一个关于这个主题的内容非常丰富的会议。

于 2013-02-26T00:42:39.403 回答