[英]Does the location background mode work in swift when the app is terminated?
Right now, I'm trying to implement the location background mode for my app. 现在,我正在尝试为我的应用程序实现位置背景模式。 When the user location is updated, I'm going to schedule a notification (eventually I'll schedule them conditionally, but for right now I'm just scheduling them so I know it works). 当用户位置更新时,我将安排一个通知(最终我将有条件地安排它们,但是现在我只是在安排他们,这样我知道它可以工作)。 I have the following code: 我有以下代码:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
currentLocation = location
}
if UIApplication.shared.applicationState == .background {
// if the app is in the background
let notif = UNMutableNotificationContent()
notif.title = "Location was updated"
var message = " "
notif.body = message
let identifier = String(arc4random())
var dc = DateComponents()
var date = Date()
date = Calendar.current.date(byAdding: .second, value: 3, to: date)!
dc.hour = Calendar.current.component(.hour, from: date)
dc.minute = Calendar.current.component(.minute, from: date)
dc.second = Calendar.current.component(.second, from: date)
let notifTrigger = UNCalendarNotificationTrigger(dateMatching: dc, repeats: false)
let request = UNNotificationRequest(identifier: identifier, content: notif, trigger: notifTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
if error != nil {
print(error!)
} else {
print("Notification scheduled!")
}
})
This works great when the app is in the background, but when the app gets terminated, my function isn't called, and the notifications aren't getting delivered. 当应用程序在后台运行时,这非常有用,但是当应用程序终止时,不会调用我的函数,并且不会传递通知。 My question is: Is this possible with Swift? 我的问题是:Swift有可能吗? Or does the locationManager
function I'm using only work if the app is backgrounded, but not terminated? 还是我正在使用的locationManager
函数仅在应用程序为后台但未终止的情况下才起作用?
Side note: I've tried taking out if UIApplication.shared.applicationState == .background
and it does not fix the problem 旁注:我曾尝试取出if UIApplication.shared.applicationState == .background
,但它不能解决问题
When you terminate the app, the normal* location services stop, until you run startUpdatingLocation
from a non-background state. 终止应用程序时,常规*位置服务将停止,直到从非后台状态运行startUpdatingLocation
。
*visit Location Service, region monitoring, significant Location Changes are not normal location tracking and are managed on the OS level not app level. *访问位置服务,区域监视,重大位置更改不是正常的位置跟踪,而是在操作系统级别而非应用程序级别进行管理。
Non-normal location tracking won't get stopped after app termination. 应用终止后,非正常位置跟踪不会停止。
That's possible. 有可能 Move the app so that location updates gets triggered. 移动应用程序,以便触发位置更新。 Check with accuracy as 100m and move your device or use simulator simulation for location. 检查精度为100m,然后移动设备或使用模拟器进行定位。 I am assuming that you have already given Use Location Always Permission 我假设您已经授予“使用位置始终”权限
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.