react-native使用leanclound消息推送的方法
iOS消息推送的基本流程
1.注冊(cè):為應(yīng)用程序申請(qǐng)消息推送服務(wù)。此時(shí)你的設(shè)備會(huì)向APNs服務(wù)器發(fā)送注冊(cè)請(qǐng)求。2. APNs服務(wù)器接受請(qǐng)求,并將deviceToken返給你設(shè)備上的應(yīng)用程序 3.客戶端應(yīng)用程序?qū)eviceToken發(fā)送給后臺(tái)服務(wù)器程序,后臺(tái)接收并儲(chǔ)存。 4.后臺(tái)服務(wù)器向APNs服務(wù)器發(fā)送推送消息 5.APNs服務(wù)器將消息發(fā)給deviceToken對(duì)應(yīng)設(shè)備上的應(yīng)用程序
使用leanclound進(jìn)行消息推送
優(yōu)勢(shì):文檔清晰,價(jià)格便宜
接入Leanclound
1.首先需要?jiǎng)?chuàng)建一個(gè)react-native項(xiàng)目
react-native init projectName
2.在leancloud創(chuàng)建一個(gè)同名項(xiàng)目,并記錄好appid和appkey


3.項(xiàng)目創(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.在項(xiàng)目目錄下新建一個(gè)文件夾,名字為pushservice,在里面添加一個(gè)js文件PushService.js,處理消息推送的邏輯,
1.在index.js初始化leanclound
import AV from 'leancloud-storage'
...
/*
*添加注冊(cè)的appid和appkey
*/
const appId = 'HT23EhDdzAfFlK9iMTDl10tE-gzGzoHsz'
const appKey = 'TyiCPb5KkEmj7XDYzwpGIFtA'
/*
*初始化
*/
AV.initialize(appId,appKey);
/*
*把Installation設(shè)為全局變量,在其他文件方便使用
*/
global.Installation = require('leancloud-installation')(AV);
...
2.iOS端配置
首先,在項(xiàng)目中引入RCTPushNotification,詳情請(qǐng)參考: Linking Libraries - React Native docs
步驟一:將PushNotification項(xiàng)目拖到iOS主目錄,PushNotification路徑:當(dāng)前項(xiàng)目/node_modules/react-native/Libraries/PushNotificationIOS目錄下
步驟二:添加libRCTPushNotification靜態(tài)庫(kù),添加方法:工程Targets-Build Phases-link binary with Libraries 點(diǎn)擊添加,搜索libRCTPushNotification.a并添加
步驟三:開啟推送功能,方法:工程Targets-Capabilities 找到Push Notification并打開
步驟四:在Appdelegate.m文件添加代碼
#import <React/RCTPushNotificationManager.h>
...
//注冊(cè)推送通知
-(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);
//請(qǐng)求權(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();
}
運(yùn)行項(xiàng)目,必須真機(jī)才能獲取到deviceToken,模擬器獲取不到,看看是否保存的deviceToken,如果保存成功,leandclound后臺(tái)能發(fā)現(xiàn)_Installation表多了一條數(shù)據(jù)

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

點(diǎn)擊發(fā)送,看是不是收到了消息.
進(jìn)行到這步驟說(shuō)明推送已經(jīng)完成了一大半了,APP當(dāng)然還需要包括以下功能:
- APP在前臺(tái)、后臺(tái)或者關(guān)閉狀態(tài)下也能收到推送消息
- 點(diǎn)擊通知能夠?qū)ο⑦M(jìn)行操作,比如跳轉(zhuǎn)到具體頁(yè)面
APP處于前臺(tái)狀態(tài)時(shí)通知的顯示
當(dāng)APP在前臺(tái)運(yùn)行時(shí)的通知iOS是不會(huì)提醒的(iOS10后開始支持前臺(tái)顯示),因此需要實(shí)現(xiàn)的功能就是收到通知并在前端顯示,這時(shí)候就要使用一個(gè)模塊來(lái)支持該功能了,那就是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文件中引入并注冊(cè)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)航,所以需要這樣寫,布局才不會(huì)亂 MessageBarAlert綁定一個(gè)alert
<View style={{flex: 1,}}>
<Nav />
<MessageBarAlert ref={(c) => { this.alert = c }} />
</View>
)
}
return <View />
}
然后再對(duì)PushService進(jìn)行修改,新增對(duì)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);
//請(qǐng)求權(quán)限
PushNotificationIOS.requestPermissions();
}
_onNotification = ( notification ) => {
var state = AppState.currentState;
// 判斷當(dāng)前狀態(tài)是否是在前臺(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
});
}
...
最后重新運(yùn)行APP并在leanclound發(fā)送一條消息,看是否在APP打開狀態(tài)也能收到通知,到了這里推送就完成了
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React Hooks: useEffect()調(diào)用了兩次問(wèn)題分析
這篇文章主要為大家介紹了React Hooks: useEffect()調(diào)用了兩次問(wèn)題分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
深入React?18源碼useMemo?useCallback?memo用法及區(qū)別分析
這篇文章主要為大家介紹了React?18源碼深入分析useMemo?useCallback?memo用法及區(qū)別,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
詳解React項(xiàng)目的服務(wù)端渲染改造(koa2+webpack3.11)
本篇文章主要介紹了詳解React項(xiàng)目的服務(wù)端渲染改造(koa2+webpack3.11),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-03-03
詳解React-Router中Url參數(shù)改變頁(yè)面不刷新的解決辦法
這篇文章主要介紹了詳解React-Router中Url參數(shù)改變頁(yè)面不刷新的解決辦法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
nodejs和react實(shí)現(xiàn)即時(shí)通訊簡(jiǎn)易聊天室功能
這篇文章主要介紹了nodejs和react實(shí)現(xiàn)即時(shí)通訊簡(jiǎn)易聊天室功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08

