iOS在Notification Service Extension中获取用户位置

问题描述 投票:1回答:1

是否可以在CoreLocation中使用UNNotificationServiceExtension框架?我尝试过的:

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)
    }
}

我在Console中拥有的全部是:enter image description here

ios swift core-location unnotificationserviceextension
1个回答
0
投票

看起来像CLLocationManagerDelegate方法从未在UNNotificationServiceExtension中被调用。但是可以从CLLocationManager location属性获取最后收到的位置:

 let locationManager = CLLocationManager()
 let lastLocation = locationManager.location
© www.soinside.com 2019 - 2024. All rights reserved.