ios - swift 2 中的 Firedate 通知

标签 ios swift uilocalnotification

我正在尝试学习 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)

然后您可以安排实际触发的通知。

参见 Apple 的 SDK:https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/IPhoneOSClientImp.html#//apple_ref/doc/uid/TP40008194-CH103-SW1

关于ios - swift 2 中的 Firedate 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34141206/

相关文章:

ios - 使用 UIStepper 进行 UILocalNotification 的时间

ios - 当应用程序被杀死而不在IOS后台运行时如何获取通知有效负载

ios - 特定时间的本地通知

ios - iPhone - 有没有办法在设备级别调整屏幕亮度

swift - 在基于 NSTableView 的 View 中删除和添加行

iphone - 设备上的空白屏幕;模拟器工作正常

swift - GPUImage2使用SolidColorGenerator作为矩形生成器

iOS UILocalNotification 仅在应用程序未运行时发出声音(无警报)

ios - 苹果源代码 - require( error == nil, bail ) 导致错误

ios - 解决 Xcode 中的内存泄漏