react-native 使用leanclound消息推送

iOS消息推送的基本流程

1.註冊:爲應用程序申請消息推送服務。此時你的設備會向APNs服務器發送註冊請求。2. APNs服務器接受請求,並將deviceToken返給你設備上的應用程序 3.客戶端應用程序將deviceToken發送給後臺服務器程序,後臺接收並儲存。 4.後臺服務器向APNs服務器發送推送消息 5.APNs服務器將消息發給deviceToken對應設備上的應用程序html

使用leanclound進行消息推送

優點:文檔清晰,價格便宜前端

接入Leanclound

1.首先須要建立一個react-native項目

react-native init projectName

2.在leancloud建立一個同名項目,並記錄好appid和appkey

3.項目建立成功後,安裝推送所需的模塊(須要cd到工程目錄)

1.使用yarn安裝node

yarn add leancloud-storage
yarn add leancloud-installation

2.使用npm安裝react

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

4.在項目目錄下新建一個文件夾,名字爲pushservice,在裏面添加一個js文件PushService.js,處理消息推送的邏輯,

1.在index.js初始化leanclound

import AV from 'leancloud-storage'
...
/* *添加註冊的appid和appkey */
const appId = 'HT23EhDdzAfFlK9iMTDl10tE-gzGzoHsz'
const appKey = 'TyiCPb5KkEmj7XDYzwpGIFtA'
/* *初始化 */
AV.initialize(appId,appKey);
/* *把Installation設爲全局變量,在其餘文件方便使用 */
global.Installation = require('leancloud-installation')(AV);

...

2.iOS端配置

首先,在項目中引入RCTPushNotification,詳情請參考:Linking Libraries - React Native docsios

步驟一:將PushNotification項目拖到iOS主目錄,PushNotification路徑:當前項目/node_modules/react-native/Libraries/PushNotificationIOS目錄下
步驟二:添加libRCTPushNotification靜態庫,添加方法:工程Targets-Build Phases-link binary with Libraries 點擊添加,搜索libRCTPushNotification.a並添加
步驟三:開啓推送功能,方法:工程Targets-Capabilities 找到Push Notification並打開
步驟四:在Appdelegate.m文件添加代碼
#import <React/RCTPushNotificationManager.h>
...

//註冊推送通知
-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
  [RCTPushNotificationManager didRegisterUserNotificationSettings:notificationSettings];
}
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  
  [RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  NSLog(@"收到通知:%@",userInfo);
  [RCTPushNotificationManager didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  NSLog(@"error == %@" , error);
  [RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
  NSLog(@"接受通知:%@",notification);
  [RCTPushNotificationManager didReceiveLocalNotification:notification];
}

5. 獲取deviceToken,並將deviceToken插入到_Installation

找到PushService文件,編寫代碼

//引用自帶PushNotificationIOS
const PushNotificationIOS = require('react-native').PushNotificationIOS;
...
class PushService {
    //初始化推送
    init_pushService = () => {
        //添加監聽事件
        PushNotificationIOS. addEventListener('register',this.register_push);
        //請求權限
        PushNotificationIOS.requestPermissions();
    }
    //獲取權限成功的回調
    register_push = (deviceToken) => {
        //判斷是否成功獲取到devicetoken
        if (deviceToken) {
            this.saveDeviceToken(deviceToken);
        } 
    }
    //保存devicetoken到Installation表中
    saveDeviceToken = (deviceToken) => {
        global.Installation.getCurrent()
            .then(installation => {
            installation.set('deviceType', 'ios');
            installation.set('apnsTopic', '工程bundleid');
            installation.set('deviceToken', deviceToken);
            return installation.save();
        });
    }
 
}

修改App.js文件 在componentDidMount初始化推送git

import PushService from './pushservice/PushService';
...
componentDidMount () {
    //初始化
    PushService.init_pushService();
}

運行項目,必須真機才能獲取到deviceToken,模擬器獲取不到,看看是否保存的deviceToken,若是保存成功,leandclound後臺能發現_Installation表多了一條數據 github

進行到這步了就已經完成了一半了,如今只須要配置推送證書便可接收推送消息,這裏就不介紹配置證書流程了,詳細步驟請參考 iOS推送證書設置 ,推送證書設置完成後,如今就去leanclound試試看能不能收到推送吧,退出APP,讓APP處於後臺狀態,
點擊發送,看是否是收到了消息.

進行到這步驟說明推送已經完成了一大半了,APP固然還須要包括如下功能:npm

  • APP在前臺、後臺或者關閉狀態下也能收到推送消息
  • 點擊通知可以對消息進行操做,好比跳轉到具體頁面

APP處於前臺狀態時通知的顯示

當APP在前臺運行時的通知iOS是不會提醒的(iOS10後開始支持前臺顯示),所以須要實現的功能就是收到通知並在前端顯示,這時候就要使用一個模塊來支持該功能了,那就是react-native-message-barreact-native

首先就是安裝react-native-message-bar模塊了bash

yarn add react-native-message-bar //yarn安裝
或者
npm install react-native-message-bar --save //npm安裝

安裝成功以後,在App.js文件中引入並註冊MessageBar

...
/* *引入展現通知模塊 */
const MessageBarAlert = require('react-native-message-bar').MessageBar;
const MessageBarManager = require('react-native-message-bar').MessageBarManager;
...
componentDidMount () {
    //初始化
    PushService.init_pushService();
    MessageBarManager.registerMessageBar(this.alert);
}
...
render() {
    const {Nav} = this.state
    if (Nav) {
      return (
       //這裏用到了導航,因此須要這樣寫,佈局纔不會亂 MessageBarAlert綁定一個alert
        <View style={{flex: 1,}}>
          <Nav /> <MessageBarAlert ref={(c) => { this.alert = c }} /> </View> ) } return <View /> } 

而後再對PushService進行修改,新增對notification事件監聽和推送消息的展現

import { AppState, NativeModules, Alert, DeviceEventEmitter } from 'react-native';
    ...
    //初始化推送
    init_pushService = () => {
        //添加監聽事件
        PushNotificationIOS. addEventListener('register',this.register_push);
        PushNotificationIOS.addEventListener('notification', this._onNotification);
        //請求權限
        PushNotificationIOS.requestPermissions();
    }
    _onNotification = ( notification ) => {
        var state = AppState.currentState;
        // 判斷當前狀態是不是在前臺
        if (state === 'active') {
            this._showAlert(notification._alert);
        }
    }
    ...
    _showAlert = ( message ) => {
        const MessageBarManager = require('react-native-message-bar').MessageBarManager;
        MessageBarManager.showAlert({
        title: '您有一條新的消息',
        message: message,
        alertType: 'success',
        stylesheetSuccess: {
            backgroundColor: '#7851B3', 
            titleColor: '#fff', 
            messageColor: '#fff'
        },
        viewTopInset : 20
    });

    }

    ...

最後從新運行APP並在leanclound發送一條消息,看是否在APP打開狀態也能收到通知,到了這裏推送就完成了

相關文章
相關標籤/搜索