4

我一直致力于在 iOS 10 中为我的应用程序设置本地通知,但在模拟器中进行测试时,我发现通知会成功安排,但在安排的时间到来时不会真正出现。这是我一直在使用的代码:

let UNcenter = UNUserNotificationCenter.current()
        UNcenter.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            // Enable or disable features based on authorization

            if granted == true {

                self.testNotification()


            }

        }

然后它运行这段代码(假设日期/时间在未来):

func testNotification () {
    let date = NSDateComponents()


    date.hour = 16
    date.minute = 06
    date.second = 00
    date.day = 26
    date.month = 1
    date.year = 2017

    let trigger = UNCalendarNotificationTrigger(dateMatching: date as DateComponents, repeats: false)

    let content = UNMutableNotificationContent()
    content.title = "TestTitle"
    content.body = "TestBody"
    content.subtitle = "TestSubtitle"

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

    UNUserNotificationCenter.current().add(request) {(error) in
        if let error = error {
            print("error: \(error)")
        } else {
            print("Scheduled Notification")
        }

    }
}

从这段代码中,它总是会打印“预定通知”,但是当通知应该被触发时,它永远不会触发。我一直找不到任何解决方法。

4

1 回答 1

1

这里有几个步骤。

  1. 确保您有权限。如果没有,请使用UNUserNotificationCenter.current().requestAuthorization它。如果您想多次弹出请求,请按照下面的答案进行操作。

  2. 如果你想显示通知前台,必须分配UNUserNotificationCenterDelegate到某个地方。

这个答案可能会有所帮助。

于 2018-07-05T15:06:04.957 回答