I've been searching the forums but can't find a good answer for Swift 3.
I'm generating a local notification via UIApplication.shared.scheduleLocalNotifiction(nofication)
, but the .background activationMode doesn't seem to work. I understand that when user clicks this notification in this mode it should bring my app in .background state and execute my code without bringing my app in foreground.
Here is my code in the viewDidLoad() of a controller (it's a copy paste from a post):
let restartAction = UIMutableUserNotificationAction()
restartAction.identifier = "xx"
restartAction.isDestructive = false
restartAction.title = "Restart"
restartAction.activationMode = .background
restartAction.isAuthenticationRequired = false
let xAction = UIMutableUserNotificationAction()
xAction.identifier = "xx1"
xAction.isDestructive = false
xAction.title = "Start"
xAction.activationMode = .background
xAction.isAuthenticationRequired = false
let categoryIdentifier = "category.identifier"
category.identifier = categoryIdentifier
category.setActions([xAction,restartAction], for: .minimal)
category.setActions([xAction, restartAction], for: .default)
let categories = Set(arrayLiteral: category)
let settings = UIUserNotificationSettings(types: [.alert, .sound], categories: categories)
UIApplication.shared.registerUserNotificationSettings(settings)
let localNotif = UILocalNotification()
localNotif.alertBody = "testBody"
localNotif.category = categoryIdentifier
// Notification will be shown after 10 second (IMPORTANT: if you want to see notification you have to close or put app into background)
localNotif.fireDate = NSDate().addingTimeInterval(20) as Date
UIApplication.shared.scheduleLocalNotification(localNotif)
In the Appdelegate
I have the following:
func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
print("Local notification received 1")
print (notification)
}
There are 2 problems with my code ( maybe related to one another ):
- When taping the notification the app is brought in foreground and then my application(:didReceieve:) is called.
- There are no option buttons attached to my notification. There should be 2 buttons which the user can click "Start" and "Restart"
What am I doing wrong?
OK, the above code is working but in ios 10 you have to pull the notification down for the options to appear. Not like the pictures where the buttons are in the notification box