Using Leancloud to realize push notification of React Native App-ios

Preface

React Native is getting more and more popular now. It is really great to build both iOS and Android applications with one set of code, and the addition development efficiency of ES6 and React is surprisingly high. Although there are many pits, they still cannot stop the market from loving it. However, the use of React Native is not always so comfortable, especially when some native functions need to be implemented with objective-c or java, which makes the majority of front-end students who have no native App development experience miserable, but there is no way to crustily write it down. Bidiu is always working hard. So React Native developers are really painful and happy, cool and tangled. However, the ability is improved rapidly in this process, so cheer up, everyone. Now it is only darkness before dawn!

What I want to share today is a small field I conquered in the development of React Native: message push.

In fact, it is impossible to push messages around when making mobile phone App. App without message push is like a company without a beautiful front desk (like our company, hey hey), which makes people have no desire to go in and have a look. . How is it possible to have a fire?

Seriously, although I found it wasn’t really difficult after pushing the React Native version of the news, it was still a little bit of a sense of accomplishment after stepping on various pits and trying numerous solutions all the way to the final success (it was relatively easy for stupid people to get satisfaction). The foreseeable difficulties in realizing the message push of React Native App lie in:

  1. Which of the many third-party push service providers is most suitable
  2. It is necessary to push Android and IOS simultaneously, and it is necessary to be very familiar with the push mechanism of both systems.
  3. Which parts need native implementation, which need js implementation, and how to realize bridging
  4. How to push the App in the background or inactive state, and how to push the message in the active state of the App?

In conclusion, I will analyze how to implement message push in detail according to the above difficulties and actual projects.

Select a service provider

There are many push service providers in the market, such as Youmeng, Aurora Push, Leancloud, Getui, Huanxin, Rong Yun, etc. We can’t have used all these choices, so what should we consider?

  1. First of all, we must support reactive. In order to verify whether these third-party services support React Native, there is no particularly good way, I can only look at their official website documents one by one. If there is no mention of React Native in the document, give up decisively (some manufacturers do not provide document search function, then it is not recommended to choose, and it is difficult to find any problems in the future).
  2. The push service needs to be stable, reliable and fast, which is not very good judgment, because everyone says they are reliable and fast, so it needs to be used in practice before judgment can be made.
  3. The document is perfect, clear, accurate and timely, and can provide official React Native push Demo.
  4. The price is reasonable (we still have to find ways to save some money for the company).

The following is a comparison of some mainstream push service providers that I have sorted out, which may not be so perfect and objective. Welcome to correct mistakes. Sorry for the manufacturers that have not been mentioned. .

Service provider React Native support no Document quality Official Demo Price
Friendship alliance Yes Poor, give up Not investigated Not investigated
Aurora Yes Lack of Demo Price
Leancloud Yes High iOS Price
xg push No (no related documents found) / / /
Ariyun push No (no related documents found) / / /
Baidu cloud push No (no related documents found) / / /
Netease Yun Xin Yes Lack of Demo Price
Yunba No (no related documents found) / / /
A push Yes Lack of Demo Price
Ring letter No (IM only) / / /
Rong Yun No (no related documents found) / / /

Of all the above manufacturers, only 4 support React Native message push. BAT does not support it as if it had been discussed. Do you think that React Native should be rejected collectively? Of the only four vendors, only one is Leancloud in terms of documents. I think the quality of documents is relatively good. Other vendors lack relevant documents to access React Native. Getui has only one small Demo, and the documents of Demo are also very crude, so it is excluded first. Aurora’s Demo should be the best, with the largest number of star, and the Demo document seems to be quite well written. Although there is no price tag, the free version seems to be enough. There is no upper limit on the number of push times, and the push speed of 200,000 articles per second is enough. It should be enough for general applications. The Demo of Netease also looks quite perfect. The document also said that in the past, the key is that the price is too expensive. The commercial version is 1800/ month. . In order to do a push is not worth it, give up! Finally, Leancloud is my personal favorite, because there have been projects used before. Whether it is the usability of documents, SDK, the reliability and speed of services or the aesthetics of websites, it can be regarded as the best among peers, and the price of commercial version 30/ day can be accepted (30/ day includes more functions and services besides push). So to sum up, only aurora push and Leancloud are worth using (welcome aurora and Leancloud to contact me for reward, hey hey). due to my personal preference, I finally chose to use Leancloud.

The concept of message push is popularized

Before we implement specific projects, it is still necessary to understand the corresponding mechanism and basic concepts of message push. I will not repeat them here. Welcome to read Leancloud’sOverview of Message Push Services.

Access to Leancloud

First we create a React Native project (Demo address in this article):

react-native init LeancloudPushDemo

And create an application with the same name in Leancloud. Just develop the version:

image

After the installation is completed, we need to install the js sdk related to Leancloud push:

$ npm install leancloud-storage --save
 
 $ npm install leancloud-installation --save

We create a services folder under the project root directory and add PushService.js files to it to manage the main logic of message push. the initial contents are as follows:

import AV from 'leancloud-storage';
 
 const appId = 'ppdriT1clcnRoda0okCPaB48-gzGzoHsz';
 const appKey = 'Qzarq5cMdWzAMjwDW4umWpBL';
 
 AV.init({
 appId: appId,
 appKey: appKey
 });
 
 const Installation = require('leancloud-installation')(AV);
 
 class PushService {
 
 }
 
 export default new PushService();

At present, PushService is still an empty class, and we will gradually enrich its functions later.
The AppId and AppKey of Leancloud can be obtained from the following page:

image

Due to the differences between iOS and Android push methods, we will implement them separately.

IOS message push

Implementing iOS message push in React Native is simpler than Android, because officials have already given itPushNotificationIOSSuch off-the-shelf components.

Configuration

First of all, according to the introduction of RCTPushNotification into iOS project, please refer to:Linking Libraries – React Native docs

Step 1: Drag the PushNotification project to the current iOS main project

image

Step 2: Add libRCTPushNotification static library

image

Step 3: Turn on Push Notification function

image

Then, modify AppDelegate.m to add push-related event proxies. please refer to:PushNotificationIOS – React Native docs,。

Get devideToken, update _Installation table

Leancloud needs to decide which device to push according to the deviceToken of iOS device, so it needs to save the deviceToken to the _Installation table. The best time to save is when App is just started, add the following code under PushService:

//Reference PushNotificationIOS
const PushNotificationIOS = require('react-native').PushNotificationIOS;

...

class PushService {
//Get iOS Message Notification Permission
_iOS_initPush = () => {
PushNotificationIOS.addEventListener('register', this._iOS_onRegister);
PushNotificationIOS.requestPermissions();
}

//Permission Obtained Successfully Callback
_iOS_onRegister = (deviceToken) => {
if (deviceToken) {
this._iOS_saveInstallation(deviceToken);
}
}

//save deviceToken to Installation
_iOS_saveInstallation = (deviceToken) => {
const info = {
apnsTopic: 'com.example',
deviceType: 'ios',
deviceToken: deviceToken
};
Installation.getCurrent()
.then(installation => installation.save(info))
.then(result => console.log(result))
.catch(error => console.error(error))
}
}

...

Revise App.js incomponentDidMountPerform initialization when:

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import PushService from './services/PushService';

type Props = {};
export default class App extends Component<Props> {

componentDidMount() {
PushService._iOS_initPush();
}

render() {
return (
<View>
<Text>Leancloud Push Demo</Text>
</View>
);
}
}

Now let’s run the project (real machine must be used, simulator cannot obtain the deviceToken) to see if the deviceToken can be obtained and saved.

After successful saving, one more record was found in the _Installation table:

image

Push certificate settings

Successfully saving the deviceToken means that we are already halfway there, but if iOS devices are to receive notifications, push certificates need to be configured. please refer to the detailed stepsIOS push certificate setup guide. Token Authentication is recommended.

After the push certificate setting is completed, you can test whether the mobile phone can receive the message notification. Leancloud provides the ability to send messages online:
image

After sending online, the mobile phone can receive the notification (accidentally revealing my wake-up time. . ):

image

Receiving and Processing of Notifications

So far, we have succeeded more than half of the time, but we want to do more. A mature application should also include the following functions:

  • App can see notification messages when running in foreground, background or closed state
  • App receives notifications in the background or in the closed state, and the App icon can display badge of the number of notifications.
  • Click on the notification to perform customized operations, such as jumping to specific pages.

Display of notifications when App opens

IOS will not remind when App receives notification when it is running at the front desk (iOS 10 starts to support display at the front desk, please refer tostackoverflow), so we need to implement our own logic to receive notifications and display them.

We choose to usereact-native-message-barTo show the notification, first install react-native-message-bar:

npm install react-native-message-bar --save

Then, introduce and register MessageBar in App.js:

...
 
 const MessageBarAlert = require('react-native-message-bar').MessageBar;
 const MessageBarManager = require('react-native-message-bar').MessageBarManager;
 
 ...
 
 componentDidMount() {
 PushService._iOS_initPush();
 MessageBarManager.registerMessageBar(this.refs.alert);
 }
 
 componentWillUnmount() {
 PushNotificationIOS.removeEventListener('register');
 MessageBarManager.unregisterMessageBar();
 }
 
 render() {
 return (
 <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
 <Text style={{ fontSize: 24 }}>Leancloud Push Demo</Text>
 <MessageBarAlert ref="alert" />
 </View>
 );
 }
 
 ...

Then, modify the PushService to add more pairsnotificationThe monitoring of events, and the method of displaying custom Alert:

...

_iOS_initPush = () => {
PushNotificationIOS.addEventListener('register', this._iOS_onRegister);
PushNotificationIOS.addEventListener('notification', this._iOS_onNotification);
PushNotificationIOS.requestPermissions();
}

_iOS_onNotification = (notification) => {
//alert if app is in front desk
if (AppState.currentState === 'active') {
this._showAlert(notification._alert);
}
}

...

_showAlert = (message) => {
const MessageBarManager = require('react-native-message-bar').MessageBarManager;
MessageBarManager.showAlert({
Title:' You have a new message',
message: message,
alertType: 'success',
stylesheetSuccess: {
backgroundColor: '#7851B3',
titleColor: '#fff',
messageColor: '#fff'
},
viewTopInset : 20
});
}

...

Finally, rerun the App, and then send a notification online. the notification can be displayed when the App is open:

image

Received notification showing Badge

To realize badge display and increase the number of notifications, it is very simple, just check it in the Leancloud console.Increment iOS badges, and then after sending the notification, a red badge will Appear on the app icon:

image

image

Remove badge

After adding badge, we need to clear it at the appropriate point in time. Leancloud also saves the number of badge on each device in the _Installation table, so clearing the badge of the device requires modifying the Installation table at the same time:

_iOS_cleanBadge = () => {
Installation.getCurrent()
.then((installation) => {
installation.set('badge', 0);
return installation.save();
})
.then((result) => {
PushNotificationIOS.setApplicationIconBadgeNumber(0);
})
.catch(error => console.log(error));
}

Customize the behavior of click notifications

Click on the notice is divided into click on the iOS system pop-up notice reminder and click on our custom MessageBar. The notification of clicking iOS system can be divided into App running in the background and App being closed. Next, we will discuss how to deal with these three states respectively:

1. App opens, click MessageBar.

React-native-message-bar providesonTapped, so all we need to do is pass in the method we want to execute. We will modify the PushService as follows:

...
 
 _iOS_onNotificationTapped = () => {
 Alert.alert('Notification Tapped');
 }
 
 _showAlert = (message) => {
 const MessageBarManager = require('react-native-message-bar').MessageBarManager;
 MessageBarManager.showAlert({
 ...
 onTapped: this._iOS_onNotificationTapped
 });
 }
 
 ...

2. App runs in the background, click on the system notification.

The realization idea is that when app receives a notification while running in the background, clicking on the notification will triggernotificationEvent, we use a temporary variable to record the current notification, and then by monitoring the change of app state, when app switches from the background to the foreground, whether the temporary variable has a value determines whether it is app opened by clicking on the notification. If it is app opened by clicking on the notification, we execute the logic we want. This is a bit of a detour. Let’s look at the code:

...

class PushService {

//Temporary variable used to record notifications
backgroundNotification = null;

_iOS_initPush = () => {
...

//Monitor app status changes
AppState.addEventListener('change', (newState) => {
if (newState === 'active') {
if (this.backgroundNotification !  = null) {
this._iOS_onNotificationTapped();
this.backgroundNotification = null;
this._iOS_cleanBadge();
}
}
});
}

...

_iOS_onNotification = (notification) => {
...

} else if (AppState.currentState === 'background') {
//app Click Notify When Running in Background
this.backgroundNotification = notification;
}
}

...

3. Click on the system notification when APP is closed.

Direct callPushNotificationIOS.getInitialNotificationWhen judging whether app is closed, click on the system message to open it:

...

_iOS_initPush = () => {
...

//When //app is closed, is it opened by clicking on system notification
PushNotificationIOS.getInitialNotification()
.then((notification) => {
if (notification) {
this._iOS_onNotificationTapped();
}
});
}

...

Conclusion

So far, the message push of iOS using Leancloud has been completed and covers the main application scenarios. For space control reasons, the Android implementation has written a separate article to share with you:

Android address:Using Leancloud to realize push notification of React Native App-android chapter

This article Demo Github address:https://github.com/MudOnTire/LeancloudPushDemoIf it helps you, star.