这对我很有用,所以我将它添加到StackOverflow以供任何未来的答案搜索者使用。
添加以下在启动计时器之前调用的实用程序方法。当我们调用AppDelegate.RestartBackgroundTimer()时,它将确保您的应用程序保持活动状态 - 即使它在后台或屏幕锁定。但是,这只会确保3分钟(如您所述):
class AppDelegate: UIResponder, UIApplicationDelegate {
static var backgroundTaskIdentifier: UIBackgroundTaskIdentifier? = nil;
static func RestartBackgroundTimer() {
if (AppDelegate.backgroundTaskIdentifier != nil) {
print("RestartBackgroundTimer: Ended existing background task");
UIApplication.sharedApplication().endBackgroundTask(AppDelegate.backgroundTaskIdentifier!);
AppDelegate.backgroundTaskIdentifier = nil;
}
print("RestartBackgroundTimer: Started new background task");
AppDelegate.backgroundTaskIdentifier = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
UIApplication.sharedApplication().endBackgroundTask(AppDelegate.backgroundTaskIdentifier!);
AppDelegate.backgroundTaskIdentifier = nil;
})
}
}
另外,启动您的应用程序时,确保以下运行。即使应用程序处于后台,它也能确保播放音频(并且在您使用它的同时,还要确保Info.plist包含“所需的背景模式”,并且“应用程序使用AirPlay播放音频或流式传输音频/视频“又名‘声音’是在其收集):
import AVFoundation;
// setup audio to not stop in background or when silent
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback);
try AVAudioSession.sharedInstance().setActive(true);
} catch { }
现在,在需要的时间。如果在后台运行超过3分钟(),你需要播放声音的类时只有30秒遗骸的背景时间。这会将背景时间重置为3分钟(只需用例如AudaCity创建一个“Silent.mp3”,然后将其拖放到您的XCode项目中即可)。
为了总结这一切,做这样的事情:
import AVFoundation
class MyViewController : UIViewController {
var timer : NSTimer!;
override func viewDidLoad() {
// ensure we get background time & start timer
AppDelegate.RestartBackgroundTimer();
self.timer = NSTimer.scheduledTimerWithTimeInterval(0.25, target: self, selector: #selector(MyViewController.timerInterval), userInfo: nil, repeats: true);
}
func timerInterval() {
var bgTimeRemaining = UIApplication.sharedApplication().backgroundTimeRemaining;
print("Timer... " + NSDateComponentsFormatter().stringFromTimeInterval(bgTimeRemaining)!);
if NSInteger(bgTimeRemaining) < 30 {
// 30 seconds of background time remaining, play silent sound!
do {
var audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Silent", ofType: "mp3")!));
audioPlayer.prepareToPlay();
audioPlayer.play();
} catch { }
}
}
}
不使用背景模式中的一种,你会在后台完成的任务(iOS上的7 3分钟)只得到3分钟,见这里:https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html,哪种背景模式适合您的情况 – 2014-09-04 06:00:14