我以这种方式管理后台任务来构建我的应用程序:
var updateTimer: NSTimer?
var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
override func viewDidLoad() {
super.viewDidLoad()
// listen for UIApplicationDidEnterBackgroundNotification
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "appDidEnterBackground:",
name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
func reinstateBackgroundTask() {
if updateTimer != nil && (backgroundTask == UIBackgroundTaskInvalid) {
registerBackgroundTask()
}
}
func registerBackgroundTask() {
backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler {
[unowned self] in
self.endBackgroundTask()
}
assert(backgroundTask != UIBackgroundTaskInvalid)
}
func endBackgroundTask() {
NSLog("Background task ended.")
UIApplication.sharedApplication().endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
func calculateNextNumber() {
switch UIApplication.sharedApplication().applicationState {
case .Active:
break
case .Background:
NSLog("Background time remaining = %.1f seconds", UIApplication.sharedApplication().backgroundTimeRemaining)
case .Inactive:
break
}
}
func appDidEnterBackground(notification:NSNotification) {
updateTimer?.invalidate()
updateTimer = nil
if backgroundTask != UIBackgroundTaskInvalid {
endBackgroundTask()
}
}
但我无法阻止后台计时器。我想使用三分钟而不是连续但是分段,例如使用5秒间隔。我不知道你能否做到,请告诉我这是否可行以及如何做到。谢谢 编辑: 我当然不清楚。我可以停下来恢复backgroundTimeRemaining的剩余时间吗? 示例
if the backgroundTimeRemaining == 168.0 {
endBackgroundTask()
}
我试过了,但它不起作用!!!