地理栅栏警报/本地通知在触发时不会唤醒锁定的电话

时间:2017-04-22 00:38:45

标签: ios swift core-location uilocalnotification geofencing

我正在制作一个使用圆形区域进行地理围栏的应用。当手机处于活动状态或应用程序处于打开状态时,地理围栏通知在模拟器和设备(运行10.3.1的iPhone 6)中都能正常工作。

在模拟器中它工作正常;当用户进入某个区域时,它会唤醒,发出声音并在锁定屏幕上显示警告。

在电话上," didEnterRegion"进入该区域时会进行委托呼叫(我记录一些消息),但是电话没有发出警报并且正在唤醒。当我按下主页按钮一次时,我可以在锁定屏幕上看到警报,但我希望它能够立即醒来并立即显示警报 - 就像我收到消息时一样。它在模拟器中工作,所以我想知道什么是错的?它已经为我工作了几次,手机和手表上都显示了警报,但95%的时间它都没有工作 - 通知会生成但只有在手动唤醒手机时才会显示

如何解决这个问题?

这是我用来创建本地通知的代码:

        // https://blog.codecentric.de/en/2016/11/setup-ios-10-local-notification/


        let location = CLLocation(latitude: item.coordinate.latitude, longitude: item.coordinate.longitude)
        GeoTools.decodePosition(location: location) {
            (address, city) in
            let content = UNMutableNotificationContent()
            content.title = "Camera nearby!"
            content.subtitle = item.id
            content.body = "\(address), \(city)"
            content.categoryIdentifier = Constants.notificationCategoryId
            content.sound = UNNotificationSound.default()
            content.threadIdentifier = item.id

            // FIXME make action for clicking notification

            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.001, repeats: false) // FIXME HACK

            let request = UNNotificationRequest(identifier: "camNotification", content: content, trigger: trigger)

            let unc = UNUserNotificationCenter.current()
            unc.removeAllPendingNotificationRequests()
            unc.add(request, withCompletionHandler: { (error) in
                if let error = error {
                    print(error)
                }
                else {
                    print("completed")
                }

            })

        }

1 个答案:

答案 0 :(得分:1)

以下是我刚刚验证的一些代码,会在发出通知时唤醒设备:

let message = "CLRegion event"
// Show an alert if application is active:
if UIApplication.shared.applicationState == .active {
    if let viewController = UIApplication.shared.keyWindow?.rootViewController {
        showSimpleAlertWithTitle(nil, message: message, viewController: viewController)
    }
}
else {
    // Otherwise app is in background, present a local notification:
    let content = UNMutableNotificationContent()
    content.body = message
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "message"

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1.0, repeats: false)
    let request = UNNotificationRequest(identifier: "com.foobar", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

真正唯一不同的是,我不打电话给removeAllPendingNotifications()所以如果你必须删除通知,我想知道removePendingNotificationRequests(withIdentifiers identifiers: [String])是否可能更精确?