iOS Swift本地通知未“弹出”

问题描述 投票:6回答:3

我正在尝试在预定时间发送本地通知。但是通知没有出现在屏幕上,而是在我向下滑动时显示在通知中心中。这就是我正在努力实现的目标。“” “” “”

此代码来自我的AppDelegate的didFinishLaunchingWithOptions()。

    // Setup local push notifications
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound], categories: nil))
    scheduleNotifications()

这是scheduleNotifications()的代码

func scheduleNotifications() {
    // create a corresponding local notification
    let notification = UILocalNotification()

    // Get today's date, time and year
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year], fromDate: NSDate())
    // Sets the fire time to 2pm/1400 hours to anticipate user for lunch time
    components.hour = 19
    components.minute = 13
    components.second = 00

    notification.fireDate = components.date             // Sets the fire date
    notification.alertBody = "Enjoyed your lunch? Don't forget to track your expenses!"
    notification.alertAction = "Add expense"
    notification.repeatInterval = NSCalendarUnit.Day    // Repeats the notifications daily

    UIApplication.sharedApplication().scheduleLocalNotification(notification)
}

任何帮助将不胜感激。谢谢!

ios xcode swift notifications local
3个回答
4
投票

您的问题是将NSDateComponents对象转换为NSDate的方式。

仅在不为components.date对象设置calendar的情况下调用NSDateComponents将返回nil

尝试使用此代替:

 notification.fireDate = calendar.dateFromComponents(components)

或者,您可以在组件对象上设置calendar属性:

components.calendar = calendar

由于将通知对象上的fireDate属性设置为nil,它将立即触发,即在您有机会关闭应用程序并锁定屏幕之前。 UILocalNotification class reference

中记录了这种行为

1
投票

我得到相同的奇怪行为。刚刚创建了一个新项目来测试您的代码。

当您将fireDate更改为:时,我注意到了什么:

notification.fireDate = NSDate(timeIntervalSinceNow: 10)             

您将得到想要的行为。

希望有所帮助!


0
投票

检查设置> YourApp>通知

验证那里的权限。 “请勿打扰”也不应处于活动状态。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.