问题
I would like to use the UserNotificationFramework on iOS 10 to send myself data only notifications -- i.e., with no user facing text or sound. Basically to use it as a persistent timer to be able to trigger the app, if running when it fires, to check for things like session timeout due to token expiry.
Kind of like an analog to a "content-available" faceless push notification in a local notification.
I have it all working except I cannot get a notification to fire without some sort of user facing data needing to be involved.
Here are the relevant pieces of the UNMutableNotificationContent of the UNNotificationRequest that is added to the UNUserNotificationCenter to trigger the notification.
// content.body = "Expiration"
// content.sound = UNNotificationSound(named: "silent-short.wav")
content.threadIdentifier = typeIdentifier
content.userInfo = ["1":"One"]
content.setValue("YES", forKey: "shouldAlwaysAlertWhileAppIsForeground")
As above the notification does not fire at all. If I uncomment either one of those lines -- does not matter which one -- it will fire. But I don't want a text notification banner displaying to the user (in or outside the app) so the first one does not help. I tried to use a silent sound, so that the system can think it is playing the sound but the user experiences nothing. But the system throws in a handy vibrate. Which in this case is not so handy. Is there a way to get the notification to not vibrate? Or any other way to get a local data only notification?
回答1:
You cannot schedule a local notification to act like a silent push notification and not show up in the notification centre. The UserNotifications
framework was designed to display data to the user in the form of a notification.
You can only achieve silent notifications using push notifications, there is no way at the moment to achieve the same functionality using local notifications.
You can use background execution if you need to execute tasks while your app is not in the foreground, but if you only need your tasks to run while your app is in the foreground, there are better ways to achieve this than using notifications. Even though your question is quite vague about what you actually want to achieve, you mention session timeout. For measuring session timeout, you can just use ordinary Date
objects, save the current date when you start the session and check the elapsed time using Date().timeIntervalSince(date: startDate)
before you would need to use your token to decide whether the token has expired or not.
来源:https://stackoverflow.com/questions/46002528/use-unnotificationrequest-usernotificationframework-for-data-only-local-notifi