王怡飞*_*王怡飞 6 background nstimer ios ios-simulator swift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
func update() {
println("Something cool")
}
}
Run Code Online (Sandbox Code Playgroud)
对于模拟器来说没关系,我会通过点击主页按钮获得连续的"Something cool".但是当我用我的iPhone调试应用程序时,它就解决了.当我点击主页按钮并使我的应用程序运行背景时,我没有得到任何东西.有人告诉我,我可以播放一段很长的空白音乐,让我的应用程序在后台运行.但我不知道如何用swift @matt在后台播放音乐
gar*_*ley 19
您可以使用beginBackgroundTaskWithExpirationHandler
获取一些后台执行时间.
class ViewController: UIViewController {
var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?
override func viewDidLoad() {
super.viewDidLoad()
backgroundTaskIdentifier = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
UIApplication.sharedApplication().endBackgroundTask(self.backgroundTaskIdentifier!)
})
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
}
func update() {
println("Something cool")
}
}
Run Code Online (Sandbox Code Playgroud)
Swift 3.0
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})
Run Code Online (Sandbox Code Playgroud)
这段代码的灵感来自于这个答案,但我移植到了swift.
这显然只在iOS 7+上运行3分钟.
我愿意打赌你不需要在后台运行计时器,你需要知道你被暂停时已经过去的时间.这比使用空声音文件更好地利用您的资源.
使用applicationWillResignActive
和applicationDidBecomeActive
确定已经过了多长时间.首先保存计时器的fireDate并使其无效applicationWillResignActive
func applicationWillResignActive(application: UIApplication) {
guard let t = self.timer else { return }
nextFireDate = t.fireDate
t.invalidate()
}
Run Code Online (Sandbox Code Playgroud)
接下来,applicationDidBecomeActive
通过将现在的时间与您在applicationWillResignActive
通话中保存的fireDate进行比较,确定计时器的剩余时间:
func applicationDidBecomeActive(application: UIApplication) {
guard let n = nextFireDate else { return }
let howMuchLonger = n.timeIntervalSinceDate(NSDate())
if howMuchLonger < 0 {
print("Should have already fired \(howMuchLonger) seconds ago")
target!.performSelector(selector!)
} else {
print("should fire in \(howMuchLonger) seconds")
NSTimer.scheduledTimerWithTimeInterval(howMuchLonger, target: target!, selector: selector!, userInfo: nil, repeats: false)
}
}
Run Code Online (Sandbox Code Playgroud)
如果你需要一个重复的,只需要数学计算出计时器应该在后台触发多少次
let howManyTimes = abs(howMuchLonger) / repeatInterval
Run Code Online (Sandbox Code Playgroud)
当我点击主页按钮并使我的应用程序在后台运行时
不,这是一个错误的假设。当您点击主页按钮时,您的应用程序不会在后台运行。您使您的应用程序在后台暂停。当您在后台时,您的代码不会运行。
应用程序可以获得在后台运行的特殊权限,只是为了执行某些有限的活动,例如继续播放音乐或继续使用核心位置。但您的应用程序不会执行这些操作,因此它会进入后台并停止。
归档时间: |
|
查看次数: |
14203 次 |
最近记录: |