在后台计数(NSTimer超过3分钟) [英] Count while in background (NSTimer for more than 3 mins)
问题描述
有什么方法可以在后台运行NSTimer 3分钟以上? 我必须创建一个使用
Is there any way to run NSTimer for more than 3 mins in background? I have to create simple app that uses
`locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion)`
扫描我的信标.当我需要检查用户距离最近的信标是否正好10秒时,我遇到了问题.我创建了
for scan my beacons. I have run into problem when I needed to check if user is exactly 10 seconds near closest beacon. I created
var timer: NSTimer?
var lastClosestBeacon: CLBeacon? {
didSet {
timer?.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: "showLocalNotification", userInfo: nil, repeats: false)
// NSRunLoop.mainRunLoop().addTimer(timer!, forMode: NSDefaultRunLoopMode)
}
}
最近的信标发生更改时,lastClosestBeacon会被设置并计划计时器.它在App中运行,并且在
When closest beacon changes lastClosestBeacon is set and timer is scheduled. It is working in App and for 3 mins when user enters background(locks phone etc.) with help from Scheduled NSTimer when app is in background? Is there any possibility to check that for more than 3 mins ?
PS.我已经添加了具有位置更新的后台模式.
PS. I have already added Background Modes with location updates.
推荐答案
您可以通过以下方式实现:
You can do it by following way:
1)首先将所需的后台模式键包含在您的Info.plist中
1) First include required background mode keys into your Info.plist
2)检查并添加以下代码行,以在iOS 9中添加位置管理器的后台工作(更新:在iOS 10中也可以使用):
2) Check and add following line of code for adding background working of location manager in iOS 9 (update: also works in iOS 10):
if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
[self.locationManager pausesLocationUpdatesAutomatically:NO];
}
3)然后创建一个新计时器,每1秒连续重复一次.
3)Then create a new timer with repeated continuously with every 1 sec.
4)在该计时器方法中,添加这两行代码.
4)In that timer method add these two line of code.
[self.locationManager stopUpdatingLocation];
[self.locationManager startUpdatingLocation];
这会使您的应用在后台运行3分钟以上.要知道,电池的使用成本可能很高.
This make your app run in background more than 3 mins. To be aware, the battery usage may be costly.
这篇关于在后台计数(NSTimer超过3分钟)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!