gpt4 book ai didi

iphone - 后台服务是 "allowed to continue running while in the background"。那为什么我不能让它工作呢?

转载 作者:行者123 更新时间:2023-11-29 04:52:23 25 4
gpt4 key购买 nike

我的应用程序确实满足将 UIBackgroundModes 设置为“应用程序播放音频”的要求。我的应用程序从 MPMusicPlayerController iPodMusicPlayer 类播放音乐。我想要完成的是允许用户设置一个计时器让音乐停止。我对此有疑问。我在 applicationDidEnterBackground 方法中实现了后台任务,如下所示:

- (void)applicationDidEnterBackground:(UIApplication *)application {
UIDevice* device = [UIDevice currentDevice];
BOOL backgroundSupported = NO;
if ([device respondsToSelector:@selector(isMultitaskingSupported)]) {
backgroundSupported = device.multitaskingSupported;
}

if (backgroundSupported) {
UIApplication* app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid) {
[app endBackgroundTask:bgTask];
}
});
}];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid) {
if (rootController.sleepTimer != nil)
self.sustainTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkTimeRemaining) userInfo:nil repeats:YES];
}

});
});
}
}

使用 checkTimeRemaining 方法:

-(void)checkTimeRemaining{
NSTimeInterval totalSeconds = rootController.timerSetInSeconds.doubleValue;
NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:rootController.startDateforSleepTimer];
NSTimeInterval remainingTime = totalSeconds - elapsedTime;
NSLog(@"remaining time %f",remainingTime);
if (remainingTime <= 0) {
[self.musicPlayer pause];
[sustainTimer invalidate];
self.sustainTimer = nil;
}
}

我没有收到任何错误,但计时器没有超出允许的 10 分钟。由于我正在播放音频(以及设置的背景模式),我应该能够在指定的时间停止音乐。关于我哪里出错了有什么想法吗?

谢谢

最佳答案

由于 beginBackgroundTaskWithExpirationHandler 只允许您执行有限长度的任务,因此您的计时器仍然受到 Apple 规定的 10 分钟时间限制。另一方面,音频框架内部允许设备在后台播放音频,直到用户停止或音频结束。

Playing Background Audio

When the UIBackgroundModes key contains the audio value, the system’s media frameworks automatically prevent the corresponding app from being suspended when it moves to the background. As long as it is playing audio or video content, the app continues to run in the background. However, if the app stops playing the audio or video, the system suspends it.

关于iphone - 后台服务是 "allowed to continue running while in the background"。那为什么我不能让它工作呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8596101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com