我正在尝试学习 Xcode 和 swift,但我无法让我的通知适用于我正在制作的简单闹钟。我使用了日期选择器并为此设置了 notification.firedate =。通知出现在通知窗口上,但警报窗口没有出现,也没有声音播放。
我还要求用户允许通知。请给我一些帮助。谢谢
AppDelegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes:[ .Alert, .Badge, .Sound], categories: nil))
return true
}
View Controller
@IBAction func alarmSet(sender: AnyObject) {
let alarmPicked = timePick.date
printTime(timePick.date)
self.notify(alarmPicked)
}
func notify(date: NSDate){
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Hour, .Minute], fromDate: date)
let notification = UILocalNotification()
notification.timeZone = NSTimeZone.localTimeZone()
notification.fireDate = calendar.dateFromComponents(comp)
notification.alertBody = "Here is the you Alarm you scheduled!"
notification.alertAction = "Dismiss"
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(notification)
self.navigationController?.popToRootViewControllerAnimated(true)
}
最佳答案
从 iOS 8+ 开始,UIApplication 要求您注册您的通知设置。如果您不这样做,它会让您安排它们,但它们永远不会触发。
你像这样注册你的设置:
let myNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(myNotificationSettings)
然后您可以安排实际触发的通知。
关于ios - swift 2 中的 Firedate 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34141206/