繁体   English   中英

iOS Swift 本地通知没有“弹出”

[英]iOS Swift Local notification not "popping up"

我正在尝试在预定时间发送本地通知。 但是通知没有出现在屏幕上,但是当我向下滑动时它显示在通知中心。

这就是我想要达到的目标 这就是我得到的。

此代码来自我的 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)
}

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

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

简单地调用components.date而不为NSDateComponents对象设置calendar将返回nil

尝试改用这个:

 notification.fireDate = calendar.dateFromComponents(components)

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

components.calendar = calendar

因为您将通知对象的fireDate属性设置为nil ,所以它会立即触发,即在您有机会关闭应用程序并锁定屏幕之前。 此行为记录在UILocalNotification 类参考中

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

当您将 fireDate 更改为:

notification.fireDate = NSDate(timeIntervalSinceNow: 10)             

你会得到你想要的行为。

希望能有所帮助!

对我来说,当手机通过电缆连接时,通知仅显示在通知中心 - 当应用程序处于前台时不显示横幅。 当电缆断开连接时,横幅会显示在应用程序上。

检查设置 > YourApp > 通知

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

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM