我的應用程序確實符合使用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分鐘。由於我正在播放音頻(連同背景模式設定),我應該可以在指定的時間停止音樂。關於我要去哪裏的任何想法都是錯誤的?
感謝
嗨,謝謝。在你描述的情況下,我還會使用iPodMusicPlayer控制器嗎?最適合學習如何實施的地方在哪裏?你認爲這是一些睡眠定時器應用程序如何實現這一目標?他們仍然可以使用iPod音樂控制器。 – sooper 2011-12-21 21:39:30