溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在react-native中利用leanclound實現(xiàn)一個消息推送功能

發(fā)布時間:2021-03-26 16:59:51 來源:億速云 閱讀:181 作者:Leah 欄目:web開發(fā)

這篇文章將為大家詳細講解有關(guān)怎么在react-native中利用leanclound實現(xiàn)一個消息推送功能,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

接入Leanclound

1.首先需要創(chuàng)建一個react-native項目

react-native init projectName

2.在leancloud創(chuàng)建一個同名項目,并記錄好appid和appkey

怎么在react-native中利用leanclound實現(xiàn)一個消息推送功能

怎么在react-native中利用leanclound實現(xiàn)一個消息推送功能

3.項目創(chuàng)建成功后,安裝推送所需的模塊(需要cd到工程目錄)

1.使用yarn安裝

yarn add leancloud-storage
yarn add leancloud-installation

2.使用npm安裝

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設(shè)為全局變量,在其他文件方便使用
*/
global.Installation = require('leancloud-installation')(AV);

...

2.iOS端配置

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

步驟一:將PushNotification項目拖到iOS主目錄,PushNotification路徑:當前項目/node_modules/react-native/Libraries/PushNotificationIOS目錄下

步驟二:添加libRCTPushNotification靜態(tài)庫,添加方法:工程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 = () => {
  //添加監(jiān)聽事件
  PushNotificationIOS. addEventListener('register',this.register_push);
  //請求權(quán)限
  PushNotificationIOS.requestPermissions();
 }
 //獲取權(quán)限成功的回調(diào)
 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初始化推送

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

運行項目,必須真機才能獲取到deviceToken,模擬器獲取不到,看看是否保存的deviceToken,如果保存成功,leandclound后臺能發(fā)現(xiàn)_Installation表多了一條數(shù)據(jù)

怎么在react-native中利用leanclound實現(xiàn)一個消息推送功能

進行到這步了就已經(jīng)完成了一半了,現(xiàn)在只需要配置推送證書即可接收推送消息,這里就不介紹配置證書流程了,詳細步驟請參考 iOS推送證書設(shè)置,推送證書設(shè)置完成后,現(xiàn)在就去leanclound試試看能不能收到推送吧,退出APP,讓APP處于后臺狀態(tài),

怎么在react-native中利用leanclound實現(xiàn)一個消息推送功能

點擊發(fā)送,看是不是收到了消息.

進行到這步驟說明推送已經(jīng)完成了一大半了,APP當然還需要包括以下功能:

  • APP在前臺、后臺或者關(guān)閉狀態(tài)下也能收到推送消息

  • 點擊通知能夠?qū)ο⑦M行操作,比如跳轉(zhuǎn)到具體頁面

APP處于前臺狀態(tài)時通知的顯示

當APP在前臺運行時的通知iOS是不會提醒的(iOS10后開始支持前臺顯示),因此需要實現(xiàn)的功能就是收到通知并在前端顯示,這時候就要使用一個模塊來支持該功能了,那就是react-native-message-bar

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

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 (
  //這里用到了導(dǎo)航,所以需要這樣寫,布局才不會亂 MessageBarAlert綁定一個alert
  <View style={{flex: 1,}}>
   <Nav />
   <MessageBarAlert ref={(c) => { this.alert = c }} />
  </View>
  )
 }
 return <View />
 }

然后再對PushService進行修改,新增對notification事件監(jiān)聽和推送消息的展示

import { AppState, NativeModules, Alert, DeviceEventEmitter } from 'react-native';
 ...
 //初始化推送
 init_pushService = () => {
  //添加監(jiān)聽事件
  PushNotificationIOS. addEventListener('register',this.register_push);
  PushNotificationIOS.addEventListener('notification', this._onNotification);
  //請求權(quán)限
  PushNotificationIOS.requestPermissions();
 }
 _onNotification = ( notification ) => {
  var state = AppState.currentState;
  // 判斷當前狀態(tài)是否是在前臺
  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
 });

 }

 ...

關(guān)于怎么在react-native中利用leanclound實現(xiàn)一個消息推送功能就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI