首页 > 技术文章 > react native 配置leancloud推送 ios版

lude1994 2020-03-26 20:10 原文

参考文章:https://blog.csdn.net/MudOnTire/article/details/81017113

 

再具体点:

 

1.安装,4版本的 leancloud-storage 会报错

"leancloud-installation": "^2.0.1", 
"leancloud-storage": "^3.7.3",

 

2.我们在项目根目录下创建services文件夹,并在其中添加PushService.js文件,用于管理消息推送的主要逻辑,初始内容如下:

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();

3.配置ios环境,打开xcode,在iOS 项目中引入 RCTPushNotification,可参考:Linking Libraries - React Native docs

      a.   在Libraries中添加

                     

 

                   b.添加第5个

                     

 

 

 

      c.添加  $(SRCROOT)/../node_modules/react-native/Libraries/PushNotificationIOS

                    

 

 

 

      d.开启Push Notification功能

       

 

 

       

      f.打开AppDelegate.m,新增以下代码

      

#import <React/RCTPushNotificationManager.h>
// Required to register for notifications
- (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.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification
{
  [RCTPushNotificationManager didReceiveRemoteNotification:notification];
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
  [RCTPushNotificationManager didReceiveLocalNotification:notification];
}



- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  return [RCTLinkingManager application:application openURL:url
                      sourceApplication:sourceApplication annotation:annotation];
}

 

 

4.获取devideToken,更新_Installation表

 

Leancloud需要根据iOS设备的deviceToken来决定推送到哪台设备,所以需要把deviceToken保存到_Installation表。而保存的最佳时机就在App刚刚启动的时候,在PushService下添加如下代码:

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

...

class PushService {
    //获取iOS消息通知权限
    _iOS_initPush = () => {
        PushNotificationIOS.addEventListener('register', this._iOS_onRegister);
        PushNotificationIOS.requestPermissions();
    }

    //权限获取成功回调
    _iOS_onRegister = (deviceToken) => {
        if (deviceToken) {
            this._iOS_saveInstallation(deviceToken);
        }
    }

    //保存deviceToken到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))
    }
}

...

 

5.修改App.js,在componentDidMount时执行初始化:

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>
    );
  }
}

 

 

6.用真机运行来获取token,运行后会自动保存token,可以在leancloud看到

 

 

7.设置ios推送证书,具体参考:https://leancloud.cn/docs/ios_push_cert.html ,推荐使用Token Authentication。

8。设置完推送证书可以进行在线推送,选择ios-测试环境

 

 

通知的接收和处理
到目前为止我们已经成功了一大半了,但是我们还想做得更多一点,一款成熟的应用还应该包括以下功能:

App在前台、后台运行或者关闭状态都能看到通知消息
App在后台或者关闭状态收到通知,App图标能显示通知个数的badge
点击通知能够进行自定义的操作,比如跳转到具体页面

 

附上完整的PushService.js文件代码

import AV from 'leancloud-storage';
import { AppState, NativeModules, Alert, DeviceEventEmitter } from 'react-native';

const PushNotificationIOS = require('react-native').PushNotificationIOS;
const AndroidPush = NativeModules.androidPushModule;

const appId = 'ppdriT1clcnRoda0okCPaB48-gzGzoHsz';
const appKey = 'Qzarq5cMdWzAMjwDW4umWpBL';

AV.init({
    appId: appId,
    appKey: appKey
});

const Installation = require('leancloud-installation')(AV);

class PushService {

    //用于记录通知的临时变量
    backgroundNotification = null;

    //iOS
    _iOS_initPush = () => {
        PushNotificationIOS.addEventListener('register', this._iOS_onRegister);
        PushNotificationIOS.addEventListener('notification', this._iOS_onNotification);
        PushNotificationIOS.requestPermissions();
        //监听app状态的改变
        AppState.addEventListener('change', (newState) => {
            if (newState === 'active') {
                if (this.backgroundNotification != null) {
                    this._iOS_onNotificationTapped();
                    this.backgroundNotification = null;
                    this._iOS_cleanBadge();
                }
            }
        });
        //app关闭时,是否通过点击系统通知打开
        PushNotificationIOS.getInitialNotification()
            .then((notification) => {
                if (notification) {
                    this._iOS_onNotificationTapped();
                }
            });
    }

    _iOS_onRegister = (deviceToken) => {
        if (deviceToken) {
            this._iOS_saveInstallation(deviceToken);
        }
    }

    _iOS_onNotification = (notification) => {
        //如果app在前台则显示alert
        if (AppState.currentState === 'active') {
            this._showAlert(notification._alert);
        } else if (AppState.currentState === 'background') {
            //app在后台运行时点击通知
            this.backgroundNotification = notification;
        }
    }

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

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

    _iOS_onNotificationTapped = () => {
        Alert.alert('Notification Tapped');
    }


    //Android
    _an_initPush = () => {
        this._an_saveInstallation();
    }

    _an_saveInstallation = () => {
        AndroidPush.saveInstaillation((installationId, error) => {
            if (installationId) {
                DeviceEventEmitter.addListener(AndroidPush.ON_RECEIVE, (notification) => {
                    console.log('receive android notification');
                    this._an_onNotificationTapped(notification);
                });
                DeviceEventEmitter.addListener(AndroidPush.ON_CUSTOM_RECEIVE, (notification) => {
                    console.log('receive custom android notification');
                    this._showAlert(JSON.parse(notification.data).alert);
                });
                DeviceEventEmitter.addListener(AndroidPush.ON_ERROR, (res) => {
                    console.log('android notification error');
                    console.log(res);
                });
            } else {
                console.log(error);
            }
        })
    }

    _an_onNotificationTapped = (notification) => {
        Alert.alert('Android Notification Tapped');
    }

    _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,
            onTapped: this._iOS_onNotificationTapped
        });
    }
}

export default new PushService();

 

 

再次感谢原作者,参考其github:https://github.com/MudOnTire/LeancloudPushDemo

 

推荐阅读