UILocalNotification 不发送

Posted

技术标签:

【中文标题】UILocalNotification 不发送【英文标题】:UILocalNotification doesn't send 【发布时间】:2016-07-15 09:45:24 【问题描述】:

我正在尝试像这样发送UILocalNotification

func sendNotifiaction() 
        let notification = UILocalNotification()
        notification.userInfo = [
            "Identifier": self.identifier!
        ]
        notification.alertTitle = "Alarm!"
        notification.alertBody = "test"
        //notification.soundName = "Temporary-bleep-sound.aiff"
        notification.category = "category"

        UIApplication.sharedApplication().scheduleLocalNotification(notification)
    

我试图在这个方法上设置一个断点,它正在被调用和运行,但是通知根本没有发送。

有人知道为什么吗?

【问题讨论】:

您是否允许该应用推送通知? @Lumialxk 我认为这就是重点,我该怎么做? 你的开火日期在哪里? 【参考方案1】:

你必须先注册通知

UIApplication.sharedApplication().cancelAllLocalNotifications()
let settings = UIUserNotificationSettings(forTypes: .Alert, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)

这是我在特定时间触发通知的演示

class AppDelegate: UIResponder, UIApplicationDelegate 

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool 
        // Override point for customization after application launch.

        UIApplication.sharedApplication().cancelAllLocalNotifications()
        let settings = UIUserNotificationSettings(forTypes: .Alert, categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(settings)

        let localNotification1 = UILocalNotification()
        localNotification1.alertBody = "Your alert message at 9:00 pm"
        localNotification1.timeZone = NSTimeZone.defaultTimeZone()
        localNotification1.fireDate = self.getNinePMDate()
        UIApplication.sharedApplication().scheduleLocalNotification(localNotification1)
        return true
    

    func getNinePMDate() -> NSDate? 
        let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
        let now: NSDate! = NSDate()
        let date21h = calendar.dateBySettingHour(21, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)
        return date21h
    

【讨论】:

【参考方案2】:

您应该在appdelegate 中实现didReceiveLocalNotification,并且您必须手动显示警报视图,并将标题和消息作为通知的alertbody

【讨论】:

以上是关于UILocalNotification 不发送的主要内容,如果未能解决你的问题,请参考以下文章

UILocalNotification 询问用户权限

接收 UILocalNotification 时从 AppDelegate 加载特定的 UIViewController

在 Swift 中将文本字段添加到 UILocalNotification

在 iOS 10 中向 UILocalNotification 添加操作

iPhone上睡眠模式下的UILocalNotification

Ios开发中UILocalNotification实现本地通知实现提醒功能