Cha*_*ong 6 xcode notifications local ios swift
我正在尝试在预定时间发送本地通知.但是通知没有出现在屏幕上,但是当我向下滑动时它会显示在通知中心.
这就是我想要实现的目标.这就是我所得到的.

这段代码来自我的AppDelegate的didFinishLaunchingWithOptions().
// Setup local push notifications
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound], categories: nil))
scheduleNotifications()
Run Code Online (Sandbox Code Playgroud)
这是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)
}
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激.谢谢!
您的问题是您将 NSDateComponents 对象转换为 NSDate 的方式。
简单地调用components.date而不calendar为NSDateComponents对象设置 a将返回nil。
尝试改用这个:
notification.fireDate = calendar.dateFromComponents(components)
Run Code Online (Sandbox Code Playgroud)
或者,您可以calendar在组件对象上设置属性:
components.calendar = calendar
Run Code Online (Sandbox Code Playgroud)
因为您fireDate将通知对象上的属性设置为nil,它会立即触发,即在您有机会关闭应用程序并锁定屏幕之前。此行为记录在UILocalNotification 类参考中
| 归档时间: |
|
| 查看次数: |
5082 次 |
| 最近记录: |