React Native

The Urban Airship React Native module allows a developer to integrate push notification services with React Native apps targeting both Android and iOS. This module is designed to be cross-platform, and applications making use of it can leverage the same code on both platforms.

Resources

Requirements

  • React Native >= 0.44.0
  • React Native cli >= 2.0.1

Setup

Android

1) Install and link the urbanairship-react-native module.

react-native install urbanairship-react-native react-native link urbanairship-react-native

Example airshipconfig.properties:

developmentAppKey = Your Development App Key
developmentAppSecret = Your Development App Secret

productionAppKey = Your Production App Key
productionAppSecret = Your Production Secret

# FCM Sender ID
fcmSenderId = Your Google API Project Number

# FCM Config File
Download the Android Firebase configuration file `google-services.json` from the
application's Firebase console into the root directory at `android/app/google-services.json`.

If your react-native application does not have an associated app in the Firebase
console - see [FCM setup instructions](https://docs.urbanairship.com/platform/push-providers/fcm/) to set one up.

# Notification customization
notificationIcon = ic_notification
notificationAccentColor = #ff0000

2) Create the airshipconfig.properties file in the applications main/assets.

iOS

1) Install and link the urbanairship-react-native module.

react-native install urbanairship-react-native react-native link urbanairship-react-native

2) Install cocoapods

$ gem install cocoapods

3) Update the app's Podfile to include the Urban Airship SDK.

Pod file:

pod 'UrbanAirship-iOS-SDK', '~>9.0'

4) Update your pods.

pod install

5) Open your apps project in the generated .xcworkspace file, add the following capabilities: - Push Notification - Background Modes > Remote Notifications

Example AirshipConfig.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>developmentAppKey</key>
  <string>Your Development App Key</string>
  <key>developmentAppSecret</key>
  <string>Your Development App Secret</string>
  <key>productionAppKey</key>
  <string>Your Production App Key</string>
  <key>productionAppSecret</key>
  <string>Your Production App Secret</string>
</dict>
</plist>

6) Create a plist AirshipConfig.plist and include it in your application’s target.

Notification Service Extension

In order to take advantage of iOS 10 notification attachments, such as images, animated gifs, and video, you will need to create a notification service extension by following the iOS Notification Service Extension Guide.

Send Your First Push Notification

import {
  UrbanAirship,
  UACustomEvent,
} from 'urbanairship-react-native'


class SampleApp extends Component {

  constructor(props) {
    super(props);

    UrbanAirship.setUserNotificationsEnabled(true)
  }

  ...
}

At this point in the guide, if you followed all the steps above you should be ready to send a test push notification to verify everything is set up properly.

Before sending a push, you must enable user notifications. The module does not enable user notifications by default in order to avoid prompting the user for permissions. But for a testing purposes, you can enable user notifications as soon as the application is ready. You may also want to set default foreground presentation options to display the notification in the foreground on iOS 10. On older iOS devices, make sure you background the app before sending the push.

Urban Airship Channel IDs

Getting the Channel ID:

var channelId = UrbanAirship.getChannelId().then(channelId => {
  console.log('Channel: ', channelId);
}));

The Channel ID is a unique identifier that ties together an application/device pair on a mobile device. The Channel ID is used to target pushes to specific devices using the Urban Airship API. Once a Channel ID is created, it will persist in the application. It may or may not change when the application is reinstalled. For more information on platform-specific operation, see the Android and iOS documentation.

Don't worry if this value initially comes back as null on your app's first run (or after clearing the application data), as the Channel ID will be created and persisted during registration. To receive an event when the Channel ID is created, see Listening for Events.

Enabling User Notifications

Enable user notifications:

UrbanAirship.setUserNotificationsEnabled(true)

The Urban Airship module makes a distinction between "user notifications", which can be seen by the user, and invisible notifications that carry only data for the app to process. Enabling or disabling user notifications is a preference often best left up to the user, so by default, user notifications are disabled.

Listening for Events

notificationResponse:

UrbanAirship.addListener("notificationResponse", (response) => {
  console.log('Notification response: ', JSON.stringify(response.notification));
  console.log('Notification response isForeground: ', response.isForeground);

  // will only be set for notification action buttons
  console.log('Notification response actionId: ', response.actionId);
});

pushReceived:

UrbanAirship.addListener("pushReceived", (notification) => {
  console.log('Received push: ', JSON.stringify(notification));
});

deepLink:

UrbanAirship.addListener("deepLink", (event) => {
  console.log('Deep link: ', event.deepLink);
});

register:

UrbanAirship.addListener("register", (event) => {
  console.log('Channel registration updated: ', event.channelId);
  console.log('Registration token: ', event.registrationToken);
});

notificationOptInStatus:

UrbanAirship.addListener("notificationOptInStatus", (event) => {
  console.log('User notifications opted in: ', event.optIn);

  // iOS only
  console.log('User notifications options: ', JSON.stringify(event.notificationOptions));
});

inboxUpdated:

UrbanAirship.addListener("inboxUpdated", (event) => {
  console.log('Message center updated. Unread count: ' + event.messageUnreadCount + 'Total message count: ' + event.messageCount);
});

Available events:

notificationResponse
Event fired when a user responds to a notification from either tapping the main notification or one of the action buttons.
pushReceived
Event fired when a push is received.
deepLink
Event fired when a new deep link is available. The app should navigate to the proper page when the event is received.
register
Event fired when channel registration updates.
notificationOptInStatus
Event fired when a user notification opt-in status changes. This event only fires in the foreground and for iOS devices includes the alert, sound, and badge opted-in options.
inboxUpdated
Event fired when the inbox is updated. The event includes the total message count and the total unread message count.

Addressing Devices

To help target specific devices or users for a notification, we have Tags, Named Users and Tag Groups.

Tags

Modifying tags:

UrbanAirship.addTag("some tag");
UrbanAirship.removeTag("other tag");

Getting tags:

UrbanAirship.getTags().then((tags) => {
  console.log('Tags: ', tags)
});

Tags allow you to attribute arbitrary metadata to a specific device. Common examples include favorites such as sports teams or news story categories.

Named Users

Setting a named user:

UrbanAirship.setNamedUser("coolNamedUserId");

Getting the named user:

UrbanAirship.getNamedUser().then((namedUser) => {
  console.log('Named User: ', namedUser)
})

Named Users allow you to associate multiple devices to a single user or profile that may be associated with more than one device, e.g., an end-user's Android phone and tablet. A device can have only one Named User, and a single Named User should not be associated with more than 50 devices. Named Users provide the ability to directly set tags on them (see Tag Groups).

By default, Named Users cannot be associated from the device. In this case if the devices attempts a Named User association, the association will fail and the module will log an error. In order to change this setting, see the Settings documentation.

Note

Associating the channel with a Named User ID, will implicitly disassociate the channel from the previously associated Named User ID, if it existed.

Tag Groups

Channel Tag Group Example:

UrbanAirship.editChannelTagGroups()
        .addTags("loyalty", ["silver-member"])
        .removeTags("loyalty", ["bronze-member"])
        .apply()

Named User Tag Group Example:

UrbanAirship.editNamedUserTagGroups()
        .addTags("loyalty", ["silver-member"])
        .removeTags("loyalty", ["bronze-member"])
        .apply()

Tag groups are configurable namespaces for organizing tags for the channel and Named User. Please view the Tag Groups documentation for more details. The Create and push to a tag group guides you through creating and using Tag Groups.

By default, Tag Groups cannot be modified from the device. In this case if a device attempts to modify Tag Groups, the modification will fail and the SDK will log an error. In order to change this setting, see the Settings documentation.

Custom Events

Example:

var customEvent = new UACustomEvent("event name", 100.0)
customEvent.addProperty("custom key", "some value");

UrbanAirship.addCustomEvent(customEvent);

Custom events let you track user activities and key conversions in your application, and tie them back to corresponding push messaging campaigns. Custom events requires analytics to be enabled. If disabled, any event that is added to analytics will be ignored. For a more detailed explanation on custom events and possible use cases, see the Custom Events topic guide.

Message Center

The default message center can be displayed at any time.

UrbanAirship.displayMessageCenter()

The message center can be dismissed:

UrbanAirship.dismissMessageCenter()

To display the inbox message:

//Includes a boolean to determine if the message should be displayed in an overlay
UrbanAirship.displayMessage("message-id", true)

To dismiss an inbox message:

//Includes a boolean to determine if the message should be dismissed from an overlay
UrbanAirship.dismissMessage(true)

To delete an inbox message:

UrbanAirship.deleteInboxMessage("message-id").then((result) => {
  console.log('Message deleted: ', result)
}).catch((err) => {
  console.log('Unable to delete message: ', err)
})

To mark an inbox message read:

UrbanAirship.markInboxMessageRead("message-id").then((result) => {
  console.log('Message marked as read: ', result)
}).catch((err) => {
  console.log('Unable to mark message as read: ', err)
})

To refresh the inbox:

UrbanAirship.refreshInbox().then((result) => {
  console.log('Inbox refreshed: ', result)
}).catch((err) => {
  console.log('Unable to refresh inbox: ', err)
})

To set the default behavior when the message center is launched from a push:

UrbanAirship.setAutoLaunchDefaultMessageCenter(false)

Urban Airship Message Center is a place in your app where you can display persistent rich messages, including HTML, video, etc. The messages are hosted by Urban Airship, and are typically displayed in standard inbox-style within your app.