我是写应用程序的新手。
刚刚写了我的第一个训练半程马拉松的应用程序。它是一个运行/步行计时器,在需要切换 Activity 模式时播放“运行”或“步行”声音,用户可以选择这些间隔。
该应用处于 Activity 状态时,可以在我的手机上正常运行,但在后台停止。我在Stackflow上搜索了很多帖子,很多人说您不应该在后台使用NStimer。
希望能有一些帮助使它在后台运行。提前致谢。
我正在使用Xcode 6.4
我的代码:
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("Counting"), userInfo: nil, repeats: true)
func Counting(){
timerCount += 1
tcSec = (timerCount % 3600 ) % 60
tcMin = (timerCount % 3600) / 60
tcHour = (timerCount / 3600)
let strSec = String(format: "%02d", tcSec)
let strMin = String(format: "%02d", tcMin)
let strHour = String(format: "%02d", tcHour)
totalTime.text = "\(strHour):\(strMin):\(strSec)"
if isRunning == true {
if runCounter != 0 {
runCounter -= 1
tcSec = (runCounter % 3600 ) % 60
tcMin = (runCounter % 3600) / 60
tcHour = (runCounter / 3600)
let strSec = String(format: "%02d", tcSec)
let strMin = String(format: "%02d", tcMin)
let strHour = String(format: "%02d", tcHour)
timerLabel.text = "\(strHour):\(strMin):\(strSec)"
} else {
isRunning = false
activityLabel.text = "Walk Time Left"
playWalkSound()
runCounter = runMax
}}
else {
if walkCounter != 0 {
walkCounter -= 1
tcSec = (walkCounter % 3600 ) % 60
tcMin = (walkCounter % 3600) / 60
tcHour = (walkCounter / 3600)
let strSec = String(format: "%02d", tcSec)
let strMin = String(format: "%02d", tcMin)
let strHour = String(format: "%02d", tcHour)
timerLabel.text = "\(strHour):\(strMin):\(strSec)"
} else {
isRunning = true
activityLabel.text = "Run Time Left"
playRunSound()
walkCounter = walkMax
}}
}
最佳答案
从iOS 7开始,您只有180秒的背景时间,但是当您点击主屏幕按钮时,您不会使应用程序在后台运行。您使应用程序在后台暂停。当您在后台时,您的代码不会运行。
根据Apple:
应用需要获得特殊权限才能在后台运行,以便执行某些受限 Activity ,例如位置,音频或蓝牙,以使其在后台保持 Activity 状态。
您可以使用一些技巧,但仍然不允许该应用超过〜180s ,只需照常实现scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
方法,然后将以下内容放入AppDelegate
中即可:
var backgroundUpdateTask: UIBackgroundTaskIdentifier = 0
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
return true
}
func applicationWillResignActive(application: UIApplication) {
self.backgroundUpdateTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
self.endBackgroundUpdateTask()
})
}
func endBackgroundUpdateTask() {
UIApplication.sharedApplication().endBackgroundTask(self.backgroundUpdateTask)
self.backgroundUpdateTask = UIBackgroundTaskInvalid
}
func applicationWillEnterForeground(application: UIApplication) {
self.endBackgroundUpdateTask()
}
180秒后,计时器将不再触发,当应用回到前台时,它将再次触发。
我强烈建议您阅读Background Execution
您可以通过Apple教程了解它的工作原理并满足您的需求。
希望对您有帮助。