在后台计数(NSTimer 超过 3 分钟)

Count while in background (NSTimer for more than 3 mins)

有没有办法让 NSTimer 在后台运行 3 分钟以上 运行? 我必须创建使用

的简单应用
 `locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion)`

用于扫描我的信标。当我需要检查用户是否正好在最近的信标附近 10 秒时,我遇到了 运行 问题。我创建了

    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 并安排计时器。它在应用程序中工作,当用户在 Scheduled NSTimer when app is in background? 的帮助下进入后台时(锁定 phone 等)持续 3 分钟 是否有可能检查超过 3 分钟?

PS。我已经添加了带有位置更新的背景模式。

自 iOS9 起,应用程序可根据请求最长 180 秒(3 分钟)的后台执行时间。 如果您将位置更新放在 Info.plist 的“所需背景模式”中,则可以无限期延长。我已经验证这样做可以让后台执行 运行 永远。但是,在您的 Info.plist 中使用此功能需要您在将您的应用程序放入 App Store 之前获得 Apple 对此后台模式的批准。

如果您不想请求位置后台模式,还有一些其他技巧您可以用来绕过 Apple 的限制,您可以在这里阅读:https://gooddevbaddev.wordpress.com/2013/10/22/ios-7-running-location-based-apps-in-the-background/

不过,请注意使用这些技巧 -- 它们在任何 iOS 升级中都会发生变化,并且使用它们可能会使您的应用程序被审阅者拒绝。

您可以通过以下方式完成:

1) 首先将所需的后台模式键包含到您的 Info.plist

2) 检查并添加以下代码行以在 iOS 9 中添加位置管理器的后台工作(更新:也适用于 iOS 10):

if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    [self.locationManager pausesLocationUpdatesAutomatically:NO];
}

3)然后创建一个新的定时器,每1秒连续重复

4)在定时器方法中添加这两行代码。

[self.locationManager stopUpdatingLocation];
[self.locationManager startUpdatingLocation];

这会使您的应用 运行 在后台运行超过 3 分钟。请注意,电池的使用成本可能很高。