简体   繁体   中英

iOS UILocalNotification scheduled, but not fired

I'm making an application where I want local notifications. And something strange is happening. I schedule the notification:

static func setNotification(body: String, departure: Double, notification_info: Dictionary<String, String> )
{
    let notification = UILocalNotification()
    notification.alertBody = body
    notification.fireDate =  NSDate(timeIntervalSinceNow: departure) 
    notification.alertAction = "ShowDetails"
    notification.userInfo = notification_info
    notification.soundName = UILocalNotificationDefaultSoundName
    UIApplication.sharedApplication().scheduleLocalNotification(notification)
    print("notification over: " + String(departure))
    print("-------" + String( notification.fireDate ))
}

I print in how much seconds i am supposed to get an notification. I go to background mode, and keep watching when I will get an notification. when the time has passed, I get no notification, even though I am sure I am in background mode. (within Xcode I look at the debug navigator > Energy Impact, and it is saying I am in background).

When I restart my phone, and run the application, it does show the notification. Everything works perfect. And then later, after some more testing and using the application, my notifications stop working again (even though the notifications are still scheduled. I am following all the scheduled notifications with:

        UIApplication.sharedApplication().scheduledLocalNotifications

I am still new with Swift, and I have no idea why this is happening. It's making me crazy not knowing why my notification is not firing, even though it is scheduled and everything...

Could anyone help me? If you need more information, please ask.

  • Edit:
    • I did set the permissions
    • The notifications are set in the AppDelegate
    • The departure time definitely is right

I made a mistake by not adding an unique ID to the notification (notification.userInfo was not always unique), and overwrites the previous scheduled notification. Thats why it something does work and sometimes doesn't.

Fixed the problem by making it unique. Thanks

Since iOS 8.0, You have to ask for permission for local notifications as remote notifications:

let notificationSettings = UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)   

See more details in Location Notifications

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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