问题描述
我是全新的写作应用。
只是写了我的第一个应用程序为半程马拉松训练。这是一个运行/步行计时器,扮演一个运行或走的声音时,它的时间切换活动模式下,用户选择的时间间隔。
该应用程序工作正常,我的手机上时,它的活跃,但在后台停止。我经历了很多Stackflow帖子搜查,许多人说你不应该在后台使用的NSTimer。结果
喜欢一些帮助越来越这在后台工作。先谢谢了。
我用X code 6.4
我的code:
定时器= NSTimer.scheduledTimerWithTimeInterval(1,目标:自我,选择:选择(计数),用户信息:无,重复:真)FUNC计数(){
timerCount + = 1
TCSEC =(timerCount%3600)60%
tcMin =(timerCount%3600)/ 60
tcHour =(timerCount / 3600)
让strSec =字符串(格式为:%02D,TCSEC)
让strMin =字符串(格式为:%02D,tcMin)
让strHour =字符串(格式为:%02D,tcHour)
totalTime.text =\\(strHour):\\(strMin):\\(strSec) 如果isRunning == TRUE {
如果runCounter!= 0 {
runCounter - = 1
TCSEC =(runCounter%3600)60%
tcMin =(runCounter%3600)/ 60
tcHour =(runCounter / 3600)
让strSec =字符串(格式为:%02D,TCSEC)
让strMin =字符串(格式为:%02D,tcMin)
让strHour =字符串(格式为:%02D,tcHour)
timerLabel.text =\\(strHour):\\(strMin):\\(strSec)
}其他{
isRunning = FALSE
activityLabel.text =走剩余时间
playWalkSound()
runCounter = runMax
}}
其他{
如果walkCounter!= 0 {
walkCounter - = 1
TCSEC =(walkCounter%3600)60%
tcMin =(walkCounter%3600)/ 60
tcHour =(walkCounter / 3600)
让strSec =字符串(格式为:%02D,TCSEC)
让strMin =字符串(格式为:%02D,tcMin)
让strHour =字符串(格式为:%02D,tcHour)
timerLabel.text =\\(strHour):\\(strMin):\\(strSec) }其他{ isRunning =真
activityLabel.text =运行剩余时间
playRunSound()
walkCounter = walkMax
}}}
由于iOS的7你只有180秒的时间背景,但是当你点击主页按钮,你不把你的应用程序在后台运行。你让你的应用程序的暂停的背景。当你在后台code不运行。
据<一个href=\"https://developer.apple.com/library/$p$prelease/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html\"相对=nofollow>苹果:
Apps need get special permission to run in the background just in order to perform certain limited activities like location, audio or bluetooth which will keep it alive in background.
There is some trick you can use , but still don't allow the app more than ~180s, just implement scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
method as usual and put the following in your 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()
}
After 180s the timer will not fire more, when the app will comeback in foreground it will start to fire again.
I strongly recommend you read the Background Executiontutorial of Apple to you can know how it works and fill your needs.I hope this help you.
这篇关于使用的NSTimer在设定的时间间隔播放声音,在后台X code6.4不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!