我使用cllocationManager并在位置管理器功能中使用DidEnter和didExit来实现GeoFencing来应用此功能。控制台正在打印“ EnterRegion被呼叫”和“出口区域被呼叫”(当模拟位置在150米左右的位置),但是没有警报(通过HandleEvent调用),直到模拟位置在300米之外。
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
if region is CLCircularRegion {
handleEvent(for: region)
// handleEventRepeat(for: region)
print("EnterRegion getting called")
}
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
if region is CLCircularRegion {
handleEvent(for: region)
print("ExitRegion Getting Called")
}
}
func handleEvent(for region: CLRegion!){
if UIApplication.shared.applicationState == .active {
guard let message = note(from: region.identifier) else { return }
window?.rootViewController?.showAlert(withTitle: nil, message: message)
} else {
guard let body = note(from: region.identifier) else { return }
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "Alarm"
notificationContent.body = body
notificationContent.sound = UNNotificationSound.default()
notificationContent.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "alarm",
content: notificationContent,
trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error: \(error)")
}
}
} }