๐ง PushNotificationIOS
Deprecated. Use the community package instead.
Handle notifications for your app, including scheduling and permissions.
Getting Startedโ
To enable push notifications, configure your notifications with Apple and your server-side system.
Then, enable remote notifications in your project. This will automatically enable the required settings.
Enable support for register
eventsโ
In your AppDelegate.m
, add:
#import <React/RCTPushNotificationManager.h>
Then implement the following in order to handle remote notification registration events:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
// This will trigger 'register' events on PushNotificationIOS
[RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
// This will trigger 'registrationError' events on PushNotificationIOS
[RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error];
}
Handle notificationsโ
You'll need to implement UNUserNotificationCenterDelegate
in your AppDelegate
:
#import <UserNotifications/UserNotifications.h>
@interface YourAppDelegate () <UNUserNotificationCenterDelegate>
@end
Set the delegate on app launch:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
return YES;
}
Foreground notificationsโ
Implement userNotificationCenter:willPresentNotification:withCompletionHandler:
to handle notifications that arrive when the app is in the foreground. Use the completionHandler to determine if the notification will be shown to the user and notify RCTPushNotificationManager
accordingly:
// Called when a notification is delivered to a foreground app.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
// This will trigger 'notification' and 'localNotification' events on PushNotificationIOS
[RCTPushNotificationManager didReceiveNotification:notification];
// Decide if and how the notification will be shown to the user
completionHandler(UNNotificationPresentationOptionNone);
}
Background notificationsโ
Implement userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:
to handle when a notification is tapped, typically called for background notifications which the user taps to open the app. However, if you had set foreground notifications to be shown in userNotificationCenter:willPresentNotification:withCompletionHandler:
, this method will also be invoked on foreground notifications when tapped. In this case, you should only notify RCTPushNotificationManager
in one of these callbacks.
If the tapped notification resulted in app launch, call setInitialNotification:
. If the notification was not previously handled by userNotificationCenter:willPresentNotification:withCompletionHandler:
, call didReceiveNotification:
as well:
- (void) userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler
{
// This condition passes if the notification was tapped to launch the app
if ([response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier]) {
// Allow the notification to be retrieved on the JS side using getInitialNotification()
[RCTPushNotificationManager setInitialNotification:response.notification];
}
// This will trigger 'notification' and 'localNotification' events on PushNotificationIOS
[RCTPushNotificationManager didReceiveNotification:response.notification];
completionHandler();
}
Reference
Methodsโ
presentLocalNotification()
โ
static presentLocalNotification(details: PresentLocalNotificationDetails);
Schedules a local notification for immediate presentation.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
details | object | Yes | See below. |
details
is an object containing:
alertTitle
: The text displayed as the title of the notification alert.alertBody
: The message displayed in the notification alert.userInfo
: An object containing additional notification data (optional).category
: The category of this notification, required for actionable notifications (optional). e.g. notifications with additional actions such as Reply or Like.applicationIconBadgeNumber
The number to display as the app's icon badge. The default value of this property is 0, which means that no badge is displayed (optional).isSilent
: If true, the notification will appear without sound (optional).soundName
: The sound played when the notification is fired (optional).alertAction
: DEPRECATED. This was used for iOS's legacy UILocalNotification.
scheduleLocalNotification()
โ
static scheduleLocalNotification(details: ScheduleLocalNotificationDetails);
Schedules a local notification for future presentation.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
details | object | Yes | See below. |
details
is an object containing:
alertTitle
: The text displayed as the title of the notification alert.alertBody
: The message displayed in the notification alert.fireDate
: When the notification will be fired. Schedule notifications using eitherfireDate
orfireIntervalSeconds
, withfireDate
taking precedence.fireIntervalSeconds
: Seconds from now to display the notification.userInfo
: An object containing additional notification data (optional).category
: The category of this notification, required for actionable notifications (optional). e.g. notifications with additional actions such as Reply or Like.applicationIconBadgeNumber
The number to display as the app's icon badge. The default value of this property is 0, which means that no badge is displayed (optional).isSilent
: If true, the notification will appear without sound (optional).soundName
: The sound played when the notification is fired (optional).alertAction
: DEPRECATED. This was used for iOS's legacy UILocalNotification.repeatInterval
: DEPRECATED. UsefireDate
orfireIntervalSeconds
instead.
cancelAllLocalNotifications()
โ
static cancelAllLocalNotifications();
Cancels all scheduled local notifications.
removeAllDeliveredNotifications()
โ
static removeAllDeliveredNotifications();
Removes all delivered notifications from Notification Center.
getDeliveredNotifications()
โ
static getDeliveredNotifications(callback: (notifications: Object[]) => void);
Provides a list of the appโs notifications that are currently displayed in Notification Center.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
callback | function | Yes | Function which receives an array of delivered notifications. |
A delivered notification is an object containing:
identifier
: The identifier of this notification.title
: The title of this notification.body
: The body of this notification.category
: The category of this notification (optional).userInfo
: An object containing additional notification data (optional).thread-id
: The thread identifier of this notification, if it has one.
removeDeliveredNotifications()
โ
static removeDeliveredNotifications(identifiers: string[]);
Removes the specified notifications from Notification Center.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
identifiers | array | Yes | Array of notification identifiers. |
setApplicationIconBadgeNumber()
โ
static setApplicationIconBadgeNumber(num: number);
Sets the badge number for the app icon on the Home Screen.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
number | number | Yes | Badge number for the app icon. |
getApplicationIconBadgeNumber()
โ
static getApplicationIconBadgeNumber(callback: (num: number) => void);
Gets the current badge number for the app icon on the Home Screen.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
callback | function | Yes | Function which processes the current badge number. |
cancelLocalNotifications()
โ
static cancelLocalNotifications(userInfo: Object);
Cancels any scheduled local notifications which match the fields in the provided userInfo
.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
userInfo | object | No |
getScheduledLocalNotifications()
โ
static getScheduledLocalNotifications(
callback: (notifications: ScheduleLocalNotificationDetails[]) => void,
);
Gets the list of local notifications that are currently scheduled.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
callback | function | Yes | Function which processes an array of objects describing local notifications. |
addEventListener()
โ
static addEventListener(
type: PushNotificationEventName,
handler:
| ((notification: PushNotification) => void)
| ((deviceToken: string) => void)
| ((error: {message: string; code: number; details: any}) => void),
);
Attaches a listener to notification events including local notifications, remote notifications, and notification registration results.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
type | string | Yes | Event type to listen to. See below. |
handler | function | Yes | Listener. |
Valid events types include:
notification
: Fired when a remote notification is received. The handler will be invoked with an instance ofPushNotificationIOS
. This will handle notifications that arrive in the foreground or were tapped to open the app from the background.localNotification
: Fired when a local notification is received. The handler will be invoked with an instance ofPushNotificationIOS
. This will handle notifications that arrive in the foreground or were tapped to open the app from the background.register
: Fired when the user registers successfully for remote notifications. The handler will be invoked with a hex string representing the deviceToken.registrationError
: Fired when the user fails to register for remote notifications. Typically occurs due to APNS issues or if the device is a simulator. The handler will be invoked with{message: string, code: number, details: any}
.
removeEventListener()
โ
static removeEventListener(
type: PushNotificationEventName,
);
Removes the event listener. Do this in componentWillUnmount
to prevent memory leaks.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
type | string | Yes | Event type. See addEventListener() for options. |
requestPermissions()
โ
static requestPermissions(permissions?: PushNotificationPermissions[]);
Requests notification permissions from iOS, prompting the user with a dialog box. By default, this will request all notification permissions, but you can optionally specify which permissions to request. The following permissions are supported:
alert
badge
sound
If a map is provided to the method, only the permissions with truthy values will be requested.
This method returns a promise that will resolve when the user accepts or rejects the request, or if the permissions were previously rejected. The promise resolves to the state of the permissions after the request has been completed.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
permissions | array | No | alert, badge, or sound |
abandonPermissions()
โ
static abandonPermissions();
Unregister for all remote notifications received via Apple Push Notification service.
You should call this method in rare circumstances only, such as when a new version of the app removes support for all types of remote notifications. Users can temporarily prevent apps from receiving remote notifications through the Settings app. Apps unregistered through this method can always re-register.
checkPermissions()
โ
static checkPermissions(
callback: (permissions: PushNotificationPermissions) => void,
);
Check which push permissions are currently enabled.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
callback | function | Yes | See below. |
callback
will be invoked with a permissions
object:
alert: boolean
badge: boolean
sound: boolean
getInitialNotification()
โ
static getInitialNotification(): Promise<PushNotification | null>;
This method returns a promise. If the app was launched by a push notification, this promise resolves to an object of type PushNotificationIOS
for the notification that was tapped. Otherwise, it resolves to null
.
getAuthorizationStatus()
โ
static getAuthorizationStatus(): Promise<number>;
This method returns a promise that resolves to the current notification authorization status. See UNAuthorizationStatus for possible values.
finish()
โ
finish(result: string);
This method is available for remote notifications that have been received via application:didReceiveRemoteNotification:fetchCompletionHandler:
. However, this is superseded by UNUserNotificationCenterDelegate
and will no longer be invoked if both application:didReceiveRemoteNotification:fetchCompletionHandler:
and the newer handlers from UNUserNotificationCenterDelegate
are implemented.
If for some reason you're still relying on application:didReceiveRemoteNotification:fetchCompletionHandler:
, you'll need to set up event handling on the iOS side:
- (void) application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
{
[RCTPushNotificationManager didReceiveRemoteNotification:userInfo fetchCompletionHandler:handler];
}
Call finish()
to execute the native completion handlers once you're done handling the notification on the JS side. When calling this block, pass in the fetch result value that best describes the results of your operation. For a list of possible values, see PushNotificationIOS.FetchResult
.
If you're using application:didReceiveRemoteNotification:fetchCompletionHandler:
, you must call this handler and should do so as soon as possible. See the official documentation for more details.
getMessage()
โ
getMessage(): string | Object;
An alias for getAlert
to get the notification's main message string.
getSound()
โ
getSound(): string;
Gets the sound string from the aps
object. This will be null
for local notifications.
getCategory()
โ
getCategory(): string;
Gets the category string from the aps
object.
getAlert()
โ
getAlert(): string | Object;
Gets the notification's main message from the aps
object. Also see the alias: getMessage()
.
getContentAvailable()
โ
getContentAvailable(): number;
Gets the content-available number from the aps
object.
getBadgeCount()
โ
getBadgeCount(): number;
Gets the badge count number from the aps
object.
getData()
โ
getData(): Object;
Gets the data object on the notification.
getThreadID()
โ
getThreadID();
Gets the thread ID on the notification.