现在,我正在尝试为我的应用程序实现位置背景模式。当用户位置更新时,我会安排一个通知(最终我会有条件地安排它们,但现在我只是安排它们,以便我知道它可以工作)。我有以下代码:
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!")
}
})
当应用程序在后台时,这非常有效,但当应用程序终止时,我的函数不会被调用,通知也不会被传递。我的问题是:斯威夫特能做到这一点吗?或者
locationManager
如果应用程序是后台的,但没有终止,我只使用work?
旁注:
我已经试过了
if UIApplication.shared.applicationState == .background
但这并不能解决问题