iOS訊息推送的基本流程
1.註冊:為應用程式申請訊息推送服務。此時你的裝置會向APNs伺服器傳送註冊請求。2. APNs伺服器接受請求,並將deviceToken返給你裝置上的應用程式 3.客戶端應用程式將deviceToken傳送給後臺伺服器程式,後臺接收並儲存。 4.後臺伺服器向APNs伺服器傳送推送訊息 5.APNs伺服器將訊息發給deviceToken對應裝置上的應用程式
使用leanclound進行訊息推送
優勢:文件清晰,價格便宜
接入Leanclound
1.首先需要建立一個react-native專案
react-native init projectName
複製程式碼
2.在leancloud建立一個同名專案,並記錄好appid和appkey
3.專案建立成功後,安裝推送所需的模組(需要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設為全域性變數,在其他檔案方便使用
*/
global.Installation = require('leancloud-installation')(AV);
...
複製程式碼
2.iOS端配置
首先,在專案中引入RCTPushNotification,詳情請參考:Linking Libraries - React Native docs
步驟一:將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初始化推送
import PushService from './pushservice/PushService';
...
componentDidMount () {
//初始化
PushService.init_pushService();
}
複製程式碼
執行專案,必須真機才能獲取到deviceToken,模擬器獲取不到,看看是否儲存的deviceToken,如果儲存成功,leandclound後臺能發現_Installation表多了一條資料
進行到這步了就已經完成了一半了,現在只需要配置推送證書即可接收推送訊息,這裡就不介紹配置證書流程了,詳細步驟請參考 iOS推送證書設定 ,推送證書設定完成後,現在就去leanclound試試看能不能收到推送吧,退出APP,讓APP處於後臺狀態, 點選傳送,看是不是收到了訊息.進行到這步驟說明推送已經完成了一大半了,APP當然還需要包括以下功能:
- APP在前臺、後臺或者關閉狀態下也能收到推送訊息
- 點選通知能夠對訊息進行操作,比如跳轉到具體頁面
APP處於前臺狀態時通知的顯示
當APP在前臺執行時的通知iOS是不會提醒的(iOS10後開始支援前臺顯示),因此需要實現的功能就是收到通知並在前端顯示,這時候就要使用一個模組來支援該功能了,那就是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 (
//這裡用到了導航,所以需要這樣寫,佈局才不會亂 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開啟狀態也能收到通知,到了這裡推送就完成了