Class
MobileNotifications
Description
Manages all incoming and outgoing notifications.
Note
You cannot instantiate this class. The NotificationCenter is a singleton instance of this class.
Methods
Name |
Parameters |
Returns |
Shared |
---|---|---|---|
category As NotificationResponseCategory |
✓ |
||
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
identifiers() As String |
✓ |
||
identifiers() As String |
✓ |
||
ParamArray options() As MobileNotifications |
✓ |
||
✓ |
|||
✓ |
|||
Latitude As Double, Longitude As Double, Radius As Double, identifier As String, mode As LocationNotification, content As NotificationContent, shouldRepeat As Boolean = False |
✓ |
||
✓ |
Events
Name |
Parameters |
Returns |
---|---|---|
settings As NotificationSettings |
||
userInfo As Dictionary |
||
notifications() As Notification |
||
error As NotificationException, notification As Notification |
||
notification As Notification |
||
notification As Notification |
||
notifications() As Notification |
||
token As String |
||
notification As Notification, action As String, textResponse As String |
Enumerations
MobileNotifications.AuthorizationOptions
AuthorizationOptions
The available ways in which your app can request notifications to be displayed when received by the target app.
Enum |
Description |
---|---|
Alert |
Shows an alert when a notification is received. |
Announcement |
Allows announcements to be read over AirPods. |
Badge |
Displays a badge on the application icon when a notification is received. |
CarPlay |
Allows received notifications to be displayed in CarPlay. |
CriticalAlert |
Ability to show notifications that override sound and banner restrictions. This option is designed for government agencies and requires a special entitlement from Apple. |
None |
Don't display the notification. |
ProvidesNotificationSettings |
Indicates to the iOS that your app provides its own notification settings screen. |
Provisional |
Ability to show notifications on a provisional basis which the user can decide to accept later. |
Sound |
Ability to play a sound when a notification is delivered. |
MobileNotifications.PresentationModes
PresentationModes
The ways in which you can request the notification received to be displayed to the user.
Enum |
---|
Alert |
AlertAndBadge |
AlertAndSound |
All |
Badge |
None |
Sound |
SoundAndBadge |
MobileNotifications.RemoteFetchResults
RemoteFetchResults
The possible responses when receiving a remote notification in the background.
Enum |
Description |
---|---|
NewData |
The background update succeeded and there was new data for the app. |
NoData |
The background update succeeded, but there was no new data for the app. |
Failed |
The background update failed, as in, your app tried to retrieve updated data and the URL request failed. |
Method descriptions
MobileNotifications.AddResponseCategory
AddResponseCategory(category As NotificationResponseCategory)
Adds a set of buttons and/or text entry fields so incoming notifications can be interactive.
This method is shared.
Add a response category that will display a dialog with a message and two buttons when the LargePizzaSale notification is received:
Var responseCategory As New NotificationResponseCategory("LargePizzaSale")
responseCategory.Caption = "Large pizzas are on sale tonight only!"
responseCategory.Actions.Add(New NotificationResponseButton("Order!", "yes")
responseCategory.Actions.Add(New NotificationResponseButton("No Thanks", "no")
NotificationCenter.AddResponseCategory(responseCategory)
MobileNotifications.Handle
Handle As Ptr
A pointer to the underlying User Notifications Center declares.
This method is shared.
MobileNotifications.RegisteredForRemoteNotifications
RegisteredForRemoteNotifications As Boolean
Returns True if the app is already registered for remote notifications.
This method is shared.
MobileNotifications.RegisterForRemoteNotifications
RegisterForRemoteNotifications
Asks the device to register the app for receiving Remote Notifications and requests a token from Apple.
This method is shared.
If the registration succeeds, the RemoteRegistrationSucceeded event will be called.
MobileNotifications.RemoveAllDeliveredNotifications
RemoveAllDeliveredNotifications
Removes all notifications that have already been delivered.
This method is shared.
MobileNotifications.RemoveAllPendingNotifications
RemoveAllPendingNotifications
Removes all pending notifications in the queue.
This method is shared.
MobileNotifications.RemoveAllResponseCategories
RemoveAllResponseCategories
Removes all response categories.
This method is shared.
MobileNotifications.RemoveDeliveredNotifications
RemoveDeliveredNotifications(identifiers() As String)
Removes the specified notifications that have already been delivered.
This method is shared.
You may wish to remove delivered notifications if no longer wish the user to see the notification in the iOS Notification Center.
MobileNotifications.RemovePendingRequests
RemovePendingRequests(identifiers() As String)
Removes the specified pending local notifications from the queue.
This method is shared.
MobileNotifications.RequestAuthorization
RequestAuthorization(ParamArray options() As MobileNotifications)
Requests from the OS permission to send local notifications.
This method is shared.
If the options you request will be visible the other (an alert, badge, sound, etc.) and the app hasn't made this request before, the OS will display a dialog asking the user to give permission. Otherwise, your request will succeed assuming the user has not otherwise disallowed the options you requested.
Because the user can change their notification settings for your app at any time, you should call RequestAuthorization in the Opening event each time your app launches.
The AuthorizationSucceeded event will be called if the request is successful.
Requesting authorization to display a notification via a badge and sound in the app's Opening event:
NotificationCenter.RequestAuthorization(MobileNotifications.AuthorizationOptions.Badge, MobileNotifications.AuthorizationOptions.Sound)
MobileNotifications.RequestDeliveredNotifications
RequestDeliveredNotifications
Requests that the OS send the app an array of notifications that it has received for the app since the last time the app was launched. The array is delivered via the DeliveredNotifications event.
This method is shared.
MobileNotifications.RequestPendingNotifications
RequestPendingNotifications
Requests that the OS send the app an array of notifications set for a future date/time that it has received for the app since the last time the app was launched.
This method is shared.
The array is delivered via the PendingNotifications event.
MobileNotifications.Send
Send(Latitude As Double, Longitude As Double, Radius As Double, identifier As String, mode As LocationNotification, content As NotificationContent, shouldRepeat As Boolean = False)
Sends the notification to the OS for delivery when the device enters or exists a region as specified by radius meters around a specific latitude and longitude.
This method is shared.
Send a notification right now:
NotificationCenter.Send(New NotificationContent("The connection has been lost."))
Send a notification every hour:
Var id As String
Var interval As New DateInterval(0, 0, 0, 1)
id = NotificationCenter.Send(interval, New NotificationContent("Are we there yet?"), True)
Send a notification in 30 seconds:
Var id As String
id = NotificationCenter.Send(30, New NotificationContent("Your access code has expired."))
Send a notification on a specific date every year:
Var id As String
Var birthday As DateTime(2890, 9, 22)
id = NotificationCenter.Send(birthday, New NotificationContent("Happy Birthday, Bilbo!"), True)
Send a notification to remind the user to visit the President of the United States when they are in town:
Var id As String
id = NotificationCenter.Send(38.897957, -77.036560, 1000, New NotificationContent("Visit the POTUS."), True)
MobileNotifications.UnregisterForRemoteNotifications
UnregisterForRemoteNotifications
Disconnects the device from Apple's Push Notification service such that sending a remote notification to the previously retrieved token will fail.
This method is shared.
Event descriptions
MobileNotifications.AuthorizationSucceeded
AuthorizationSucceeded(settings As NotificationSettings)
Your app's request to send local notifications was granted.
MobileNotifications.BackgroundNotificationReceived
BackgroundNotificationReceived(userInfo As Dictionary)
A remote notification has been received indicating that the app should retrieve some data in the background.
According to Apple, your app is given approximately 30 seconds to download the new data. The return value is a hint to iOS so it knows whether or not to repeat the request.
MobileNotifications.DeliveredNotifications
DeliveredNotifications(notifications() As Notification)
Delivers an array of notifications for the app that have been received by the OS since the last the app was launched.
This event is called in response to a call to RequestDeliveredNotifications.
MobileNotifications.Error
Error(error As NotificationException, notification As Notification)
Occurs when the Notification could not be sent.
There are three reasons why an error occurs:
There is an error sending a particular Notification, in which case Notification will contain the Notification object.
The user has declined to allow local notifications. in which case, the Notification will be Nil.
The user has declined to allow or the device is not capable of receiving remote notifications in which case, Notification will be Nil.
MobileNotifications.NotificationReceived
NotificationReceived(notification As Notification) As PresentationModes
A local Notification has been received while your app was in the foreground.
Return the way in which the notification should be presented via a PresentationModes value.
MobileNotifications.NotificationSent
NotificationSent(notification As Notification)
The local Notification was successful scheduled.
This event is called after the Send method is used to schedule a notification.
MobileNotifications.OpenNotificationsSettings
OpenNotificationsSettings
The user has tapped on the link on the notifications settings panel in the Settings app.
If, when requesting authorization to send notifications, you included the ProvidesNotificationSettings option, a link to your app will be included in the app's notification settings in the Notifications section of the Settings app. Should the user tap on that link, this event will fire. Your app should display it's own custom notification settings dialog.
MobileNotifications.PendingNotifications
PendingNotifications(notifications() As Notification)
Delivers an array of notifications for the app that are set for a future date/time and have been received by the OS since the last the app was launched.
This event is called in response to a call to RequestPendingNotifications.
MobileNotifications.RemoteRegistrationSucceeded
RemoteRegistrationSucceeded(token As String)
The request to send remote notifications succeeded.
This event is called in response to calling the RegisterForRemoteNotifications method.
The device token passed was created by and registered with Apple's Push Notification service (APNs). The token is unique to this instance of your app. If the user reinstalls the app for any reason, calling RegisterForRemoteNotifications will generate a new token.
This token is required in order to send remote notifications to the instance of the app the token represents. Therefore you will want to store the token in the database where you keep information about the user.
Warning
Do not store the token on the device as this presents a security risk.
MobileNotifications.UserResponded
UserResponded(notification As Notification, action As String, textResponse As String)
A local notification was received while your app was in the background and the user responded to the notification by tapping on it.
By default this event will occur if the user touches the notification to bring your app to the foreground. You may add other actions by adding a NotificationResponseCategory.
Notes
This class can't be instantiated. Instead add the NotificationCenter to your project (via the Insert menu) and then use that singleton to send and receive notifications. You should also always use the NotificationCenter singleton when calling any and all methods from MobileNotifications including the shared methods. Using the MobileNotifications class directly will result in events failing to be called.
There are two types of notifications: local and remote. Local notifications are those sent from your app to itself. For example, you might be scheduling a notification to remind the user to take some important action at a future date. Remote notifications are those received by your app from outside of itself.
Before you can send a notification or receive a remote one, you must get authorization to do so. How this is done depends on whether you are using local or remote notifications.
Getting local notification authorization
Authorization for local notifications is done by calling the NotificationCenter.RequestAuthorization method. If it's successful, the AuthorizationSucceeded event will fire. This request needs to only be made once each time the app is launched therefore it should be done in the App.Opening event. When you request authorization, you also indicate the ways in which you wish the notification to be displayed. Having said that, your notification may end up not being displayed as you wished because of the user's notification preferences for your app, the device is in lower power mode, turned off, etc.
Sending local notifications
There are three types of notifications that can be sent from an app:
Time Interval Notifications are delivered based on the number of seconds between the request and the delivery. Xojo allows you to use and Integer or a DateInterval to specify the interval. These use the TimeIntervalNotification class.
Calendar Notifications are delivered based on a calendar date, specified with a DateTime. These use the CalendarNotification class.
Location Notifications are delivered when the device moves into or out of a circular region defined by geographic coordinates and a radius. These use the LocationNotification class.
After creating a type of notification, send it with the NotificationCenter.Send method. If it was successfully sent, the NotificationCenter.NotificationSent event will be called.
When you send a notification, what you are really doing is scheduling it to be delivered by the OS itself. See the notification type classes above for example code.
Sending remote notifications
Apple's Push Notification Service uses different servers for testing versus shipping apps. Which one it uses is based upon whether or not you have turned on Build Settings > Build For App Store. See Apple's documentation for more details.
Receiving notifications
When a notification arrives, how your app handles it depends on whether the app is in the foreground or not. If your app is in the foreground, the NotificationCenter.NotificationReceived event will be called and you can return a value that describes how you wish the notification to be presented to the user. If your app is in the background or not running at all, the OS will display the notification. When the user taps on it, only then will your app's NotificationCenter.UserResponded event will be called. You can also create your own custom user interfaces to provide more options when displaying notifications (called Response Categories) by calling the NotificationCenter.AddResponseCategory method.
Registering to receive remote notifications
To be able to send remote notifications to your app, you will need to:
Sign-in to your Apple Developer account and add remote notifications to your app's identifier.
Sign up with a service that will act as an agent for sending remote notifications.
Have your app register with Apple's Push Notification (APN) service to receive remote notifications. Each time your app launches, first check to see if the app is already registered to receive remote notifications by calling NotificationCenter.RegisteredForRemoteNotifications method from the App.Opening event. If this method returns False, call the NotificationCenter.RegisterForRemoteNotifications method. The NotificationCenter.RemoteRegistrationSucceeded event will be called if the registration is successful, returning a unique token. This token is required to be able to send remote notifications to this particular instance of the app. Store this token in your database where you keep user account information.
Enable the enable the Remote Notifications entitlement for your project.
Warning
Do NOT store the token on the device as this is a security risk.
Receiving background only remote notifications
Remote notifications provide the option to be sent as background only meaning that they will not present any user interface to the user. These are used when you need the app to take an action that does not require user interaction such as updating some local data. When a background only remote notification is received, the NotificationCenter.BackgroundNotificationReceived event is called.
Time limit for responding to notifications
When you receive a notification while your app is in the background or not running at all, or a background only remote notification, the OS will give your app about 30 seconds to complete the event. If your app takes longer, the OS may terminate the app so whatever you do, do it quickly.
Testing remote notifications
Testing of remote notifications can be done locally via the simulator or on device or through Apple's Push Notification service as described earlier.
The iOS Simulator cannot receive remote notifications. However, you can simulate a remote notification for testing purposes by putting the text below into a file named with a .apns extension and dragging it into the simulator:
{
"Simulator Target Bundle": "your.bundle.identifier.here",
"aps": {
"alert": {
"title" : "Chicken Avocado Taco Platter",
"subtitle" : "All New Flavors!",
"body" : "Special - Today Only $4.99"
}
}
}
To test locally on a physical device, use this free utility.
Compatibility
iOS projects on the iOS operating system.
See also
Object parent class; CalendarNotification, LocationNotification, Notification, NotificationContent, NotificationSettings, NotificationException, NotificationResponseCategory, NotificationSettings, RemoteNotification, and TimeIntervalNotification classes.