在UNNotificationServiceExtension中可以使用CoreLocation框架吗?我尝试过的:
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
private let locationManager = CLLocationManager()
override func didReceive(_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
os_log("%{public}@",
log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
type: OSLogType.debug,
"Push received")
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
}
override func serviceExtensionTimeWillExpire() {
os_log("%{public}@",
log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
type: OSLogType.debug,
"Task expired")
locationManager.stopUpdatingLocation()
locationManager.delegate = nil
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}extension NotificationService: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locations.forEach {
os_log("%{public}@",
log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
type: OSLogType.debug,
$0.horizontalAccuracy)
}
for location in locations {
let locationAge = -location.timestamp.timeIntervalSinceNow
if locationAge < 5 {
os_log("%{public}@",
log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
type: OSLogType.debug,
"Send")
locationManager.stopUpdatingLocation()
locationManager.delegate = nil
contentHandler?(UNNotificationContent())
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
os_log("%{public}@",
log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
type: OSLogType.debug,
error.localizedDescription)
}
}我在控制台里得到的只有:

发布于 2020-05-29 04:13:22
看起来在UNNotificationServiceExtension中永远不会调用CLLocationManagerDelegate方法。但是可以从CLLocationManager location属性中获取最后接收到的位置:
let locationManager = CLLocationManager()
let lastLocation = locationManager.location发布于 2020-07-15 21:17:02
您需要实现一个后台url会话。它有助于延迟扩展到期,在这种情况下,直到位置更新被传递(以及任何其他编写的后期处理)。
private lazy var urlSession: URLSession = {
let config = URLSessionConfiguration.background(withIdentifier: "MySession")
config.sessionSendsLaunchEvents = true
return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()https://stackoverflow.com/questions/61796055
复制相似问题