Push Notifications with AWS Amplify
Push notifications play an important role in any application. This can dramatically increase user engagement.
Setting up push notifications from scratch can be a little tricky. Fortunately, Amplify provides push notification services and SDKs for our apps. In this tutorial, we will learn how to integrate this service into our application.
Create a new project ⚛️
npx react-native init amplifyPush
cd amplifyPush
In the root directory of the React Native project, initialize AWS Amplify
amplify init
We answer questions:
The project was initialized
We add dependencies:
yarn add aws-amplify @aws-amplify/pushnotification
npm install --save aws-amplify @aws-amplify/pushnotification
We link the push notification dependency using the command:
react-native link @aws-amplify/pushnotification
netinfo
library. You can add it to your project with the following command (if you don't have one):yarn add @react-native-community/netinfo
npm install --save @react-native-community/netinfo
Android - Setting up Firebase
- Open Firebase Console.
- Open or create a new project for further actions.
- Select
Cloud Messaging
from the toolbar.
- Click on Android and follow these steps:
- Fill out the form and register the application. The
android package name
can be found inandroid / app / build.gradle
. Stored inapplicationId
look like this:
gradle title="android/app/build.gradle"
defaultConfig {
applicationId "com.amplifypush"
}
Upload the config file to
android / app
.Add Firebase SDK. Consider
<project>
android
and<app-module>
app
directory to react native project. Don't forget to add the latest version of
firebase-messaging
from here andfirebase-analytics
independencies
Run the project in Android and you will see confirmation from Firebase. (you can skip this step). 5. Open
android / app / src / main / AndroidManifest.xml
and add the following code toapplication
:
<!--[START Push notification config -->
<!-- [START firebase_service] -->
<service
android:name="com.amazonaws.amplify.pushnotification.RNPushNotificationMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<!-- [END firebase_service] -->
<!-- [START firebase_iid_service] -->
<service
android:name="com.amazonaws.amplify.pushnotification.RNPushNotificationDeviceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<receiver
android:name="com.amazonaws.amplify.pushnotification.modules.RNPushNotificationBroadcastReceiver"
android:exported="false" >
<intent-filter>
<action android:name="com.amazonaws.amplify.pushnotification.NOTIFICATION_OPENED"/>
</intent-filter>
</receiver>
<!-- [END Push notification config -->
Настройка Amplify для FCM
- Add a push notification service using the following command in your project directory:
amplify add notifications
- Please select
FCM
:
? Choose the push notification channel to enable.
APNS
❯ FCM
Email
SMS
- Enter the exact name of the resource (or just hit enter without filling anything).
- You will be asked for
ApiKey
. To do this, you need to follow these steps:
- Open Firebase Console and open the app you created in the previous steps.
- Click on the icon in the
Project Overview
section in the toolbar and selectProject settings
. -Select theCloud Messaging
tab and copy the valueServer key
.
- Insert the requested values for
ApiKey
. - After completing the configuration, run
amplify push
.
iOS - Setting up
- Install
@react-native-community/push-notification-ios
:
yarn add @react-native-community/push-notification-ios
npm install --save @react-native-community/push-notification-ios
Run the following command to iOS:
cd ios && pod install && cd ..
Add iOS notifications with the command
amplify add notifications
:- Choose
APNS
:
? Choose the push notification channel to enable.
> APNS
FCM
Email
SMS- You will then be prompted for an authentication method. It is recommended to select a certificate.
? Choose authentication method used for APNs (Use arrow keys)
> Certificate
KeyIf you selected a certificate, you will be prompted for the path to the .p12 certificate. (You can use this tutorial).
Run
amplify push
.Discover
.xcworkspace
with XCode.Select a project and select a project name in the
TARGETS
section. SelectSigning & Capabilities
and press the+
in front of theCapability
. SelectBackground Mode - Remote Notifications
.
- Choose
Application setup
As stated earlier, Analytics
needs to be integrated with notifications. This will help track notifications. Although custom properties can be used, it is recommended that you use the aws-exports
file.
In App.js
add the following configuration:
...
import Amplify from 'aws-amplify'
import PushNotification from '@aws-amplify/pushnotification'
import awsconfig from './aws-exports'
Amplify.configure(awsconfig)
PushNotification.configure(awsconfig)
...
Working with API
We usually want to send push notifications to specific users for various purposes. The API provides us with various methods to handle our users and push notifications.
onRegister
Each device can be recognized with a push token, with which you can specify the device for which you want to receive a push notification. When the user opens the application for the first time, the pushed token is retrieved and stored on the device. You should be aware that this method may be called again in the future, so you should be prepared for this situation to update your data accordingly.
You can add the following code to App.js
:
PushNotification.onRegister(token => {
console.log('in app registration', token)
PushNotification.updateEndpoint(token)
})
attention: On Android, there might be a problem that this method will never be called! However workaround can be like this wherever you need a token:
...
import {NativeModules} from 'react-native'
...
NativeModules.RNPushNotification.getToken((token) => {
console.log(`PushToken: ${token}`)
})
...
onNotification
If you want to do something when a notification is received, the onNotification
method is for actions based on the received notification. Keep in mind that the structure of notification objects is different from Android and iOS. On iOS, you should use the finish
method. You can add the following code to App.js
:
...
import PushNotificationIOS from '@react-native-community/push-notification-ios'
...
PushNotification.onNotification((notification) => {
console.log('in app notification', notification)
if (Platform.OS === 'ios') {
notification.finish(PushNotificationIOS.FetchResult.NoData)
}
})
onNotificationOpened
A common scenario is when a user opens a push notification, onNotificationOpened
is called. App.js
looks like this:
PushNotification.onNotificationOpened(notification => {
console.log('the notification is opened', notification)
})
requestIOSPermissions
Push notification only works on a real device and will not receive any notifications unless the end user gives permission. requestIOSPermissions
is needed to get this permission. It can be called without any parameters, or you can customize the object like this:
PushNotification.requestIOSPermissions()
// or
PushNotification.requestIOSPermissions({
alert: true,
badge: true,
sound: false
})
Testing
First of all, we want to take a look at the file App.js
.
import React from 'react'
import { SafeAreaView, Platform, Text, NativeModules } from 'react-native'
import PushNotificationIOS from '@react-native-community/push-notification-ios'
import Analytics from '@aws-amplify/analytics'
import Amplify from 'aws-amplify'
import PushNotification from '@aws-amplify/pushnotification'
import awsconfig from './aws-exports'
Amplify.configure(awsconfig)
PushNotification.configure(awsconfig)
PushNotification.onRegister(async token => {
console.log('in app registration', token)
PushNotification.updateEndpoint(token)
})
// In case PushNotification.onRegister didn't work
NativeModules.RNPushNotification.getToken(token => {
console.log(`PushToken: ${token}`)
})
PushNotification.onNotification(notification => {
console.log('in app notification', notification)
if (Platform.OS === 'ios') {
notification.finish(PushNotificationIOS.FetchResult.NoData)
}
})
PushNotification.onNotificationOpened(notification => {
console.log('the notification is opened', notification)
})
const endpointId = Analytics.getPluggable('AWSPinpoint')._config.endpointId
console.log(`endpoint ID: ${endpointId}`)
if (Platform.OS === 'ios') {
PushNotification.requestIOSPermissions()
}
const App: () => React$Node = () => {
return (
<SafeAreaView>
<Text>Push Notification</Text>
</SafeAreaView>
)
}
export default App
Launching the project:
react-native run-android
react-native run-ios
To go further, we need one of the endpoint ID
or Push Token
. Explained in detail here endpoint
in aws
services:
Endpoint
represents a destination to which you can send messages, such as a mobile device, email address, or phone number.
Push Token
it is a unique identifier that is generated and assigned from GCM
(Android) or APNS
(iOS) to your application on a specific device.
The most obvious difference between the two is that the endpoint
is generated from aws
and defines the application on the device regardless of platform (iOS / Android). But the token, depending on the platform, is generated either from Apple
or Google
.
We use console.log
for copying and save these keys for the next steps. Switch to development mode and copy the following values to the console:
While there are several ways to send a test push notification to a specific device, we'll explore the easiest way.
- Run the following command at the root of the project:
amplify notification console
- The application console will automatically open in the browser.
- Select
Test messaging
in the left sidebar:
In the
Channel
section, selectPush notifications
.The
Destinations
section looks like this:Destination type
determines whether you want to useEndpoint IDs
orDevice Tokens
(orPush token
in the previous steps) in the next text input.Insert the token you want to use based on the
Destination type
.If you selected
Endpoint IDs
and used an endpoint, thePush Notification Service
can automatically detect your device. Otherwise, if you usedDevice token
, selectAPNS
for IOS andFCM
for Android.You can fill in the
Message
section as shown below and click the buttonSend message
.You will receive a success message as shown below. After a couple of seconds, you will see a push notification on your device:
Done
Links:
Setting up Android Push Notifications with AWS Amplify