iOS 10本地通知未显示

5

我一直在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")
        }

    }
}

从这段代码中,它总是打印出“Scheduled Notification”,但当通知应该被触发时,它从未被触发。我一直无法找到任何解决方法。


当通知应该被触发时,您的应用程序是否在前台? - bhakti123
不,我确保在通知触发之前退出应用程序。我已经尝试过当应用程序在后台运行时,完全关闭它以及当锁定屏幕显示时。但都没有成功。 - Simply Epic
你是不是手动改变设备的时间来进行测试? - bhakti123
1
尝试将标识符“testId”更改为其他内容,具有相同标识符的通知将被拒绝。因此,可能是第一次安排了通知,这就是为什么它拒绝其他通知的原因。 - bhakti123
你在新项目中更改了应用程序的Bundle ID吗? - Makalele
显示剩余5条评论
1个回答

2
以下是几个步骤:
  1. 确保你拥有权限。如果没有,使用UNUserNotificationCenter.current().requestAuthorization来获取该权限。或者按照下面的答案,如果您想要多次显示请求弹出窗口。

  2. 如果您想在前台显示通知,则需要将UNUserNotificationCenterDelegate分配给某个位置。

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

将NUserNotificationCenter.current().delegate分配给后台推送通知会“破坏”它(UIApplicationDelegate.didReceiveRemoteNotification()不再被调用)... 据我所知,目前没有适当的方法来实现前台通知。 - Erkki Nokso-Koivisto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接