react-native集成极光推送

2023-05-16

目录

  • 环境
  • 一、安装
  • 二、配置
    • 2.1 Android
    • 2.2 IOS
      • 2.2.1 pod
      • 2.2.2 手动方式
  • 总结

环境

  "react": "16.13.1",
  "react-native": "0.63.2",
  "jcore-react-native": "^1.9.0",
  "jpush-react-native": "^2.8.2",
 

一、安装

npm install jpush-react-native --save
//确保你的项目已经安装了该库
npm install jcore-react-native --save

安装完成后

react-native link
或
react-native link jpush-react-native
react-native link jcore-react-native

二、配置

2.1 Android

  • android/app/build.gradle
    android {
         defaultConfig {
             applicationId "yourApplicationId"           //在此替换你的应用包名
             ...
             manifestPlaceholders = [
                     JPUSH_APPKEY: "yourAppKey",         //在此替换你的APPKey
                     JPUSH_CHANNEL: "yourChannel"        //在此替换你的channel,可使用developer-default保持默认
             ]
         }
     }
dependencies {
      ...
      implementation project(':jpush-react-native')  // 添加 jpush 依赖
      implementation project(':jcore-react-native')  // 添加 jcore 依赖
  }
  • android/settings.gradle
	include ':jpush-react-native'
	project(':jpush-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/jpush-react-native/android')
	include ':jcore-react-native'
	project(':jcore-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/jcore-react-native/android')
  • android\app\src\main\AndroidManifest.xml
<meta-data
	android:name="JPUSH_CHANNEL"
	android:value="${JPUSH_CHANNEL}" />
<meta-data
	android:name="JPUSH_APPKEY"
	android:value="${JPUSH_APPKEY}" />    
  • android\app\src\main\java\com\bm\mm\MainApplication.java
...
import java.util.List;
import cn.jiguang.plugins.push.JPushModule;
// import cn.jpush.reactnativejpush.JPushPackage; 
//我看了几篇博客导包都是上面这个地址,在新版本中编译会报错,地址如下:
import cn.jiguang.plugins.push.JPushPackage;


public class MainApplication extends MultiDexApplication implements ReactApplication {

    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
               ...

                @Override
                protected List<ReactPackage> getPackages() {
                    return Arrays.asList(
                           ...
                           new JPushPackage()
                    );
                }

            	...
            };

	...

    @Override
    public void onCreate() {
        super.onCreate();
        SoLoader.init(this, /* native exopackage */ false);
        //调用此方法:点击通知让应用从后台切到前台
        JPushModule.registerActivityLifecycle(this); 
    }
}


2.2 IOS

首先是配置好ios的推送证书(官方文档说的很详细)
极光ios证书设置指南.

2.2.1 pod

pod install
  • 注意:如果项目里使用pod安装过,请先执行命令
	pod deintegrate

2.2.2 手动方式

  • 检查项目中是否开启了Push Notification

  • Capabilities - Push Notification
    在这里插入图片描述

  • Build Phases - Link Binart With Libraries
    在这里插入图片描述

  • AppDelegate.m

...
#import <RCTJPushModule.h>
#import "JPUSHService.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用 idfa 功能所需要引入的头文件(可选)
#import <AdSupport/AdSupport.h>
...
@interface AppDelegate ()<JPUSHRegisterDelegate>
  • 在didFinishLaunchingWithOptions中添加如下代码
// 注册apns通知
   if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) { // iOS10 {
 #ifdef NSFoundationVersionNumber_iOS_9_x_Max
     JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
     entity.types = UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound;
     [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
 #endif
   } else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
     //可以添加自定义categories
     [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
     UIUserNotificationTypeSound |
     UIUserNotificationTypeAlert)
     categories:nil];
   } else {
     //iOS 8以前 categories 必须为nil
     [JPUSHService registerForRemoteNotificationTypes:(UNAuthorizationOptionBadge |
     UNAuthorizationOptionSound |
     UNAuthorizationOptionAlert)
     categories:nil];
   }
   //此处appKey是你在极光上创建应用后的appkey,channel可以默认使用nil,
   //apsForProduction是指生产/开发环境使用推送
   [JPUSHService setupWithOption:launchOptions appKey:@"youAppKey"
                         channel:nil apsForProduction:YES]

在sourceURLForBridge后面添加如下代码

#pragma mark -注册 APNS 成功并上报 DeviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  [JPUSHService registerDeviceToken:deviceToken];
}

//iOS 7 APNS
- (void)application:(UIApplication *)application didReceiveRemoteNotification:  (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  // iOS 10 以下 Required
  NSLog(@"iOS 7 APNS");
  [JPUSHService handleRemoteNotification:userInfo];
  [[NSNotificationCenter defaultCenter] postNotificationName:J_APNS_NOTIFICATION_ARRIVED_EVENT object:userInfo];
  completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark -iOS 10 前台收到消息
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center  willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  NSDictionary * userInfo = notification.request.content.userInfo;
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    // Apns
    NSLog(@"iOS 10 APNS 前台收到消息");
    [JPUSHService handleRemoteNotification:userInfo];
    [[NSNotificationCenter defaultCenter] postNotificationName:J_APNS_NOTIFICATION_ARRIVED_EVENT object:userInfo];
  }
  else {
    // 本地通知 todo
    NSLog(@"iOS 10 本地通知 前台收到消息");
    [[NSNotificationCenter defaultCenter] postNotificationName:J_LOCAL_NOTIFICATION_ARRIVED_EVENT object:userInfo];
  }
  //需要执行这个方法,选择是否提醒用户,有 Badge、Sound、Alert 三种类型可以选择设置
  completionHandler(UNNotificationPresentationOptionAlert);
}

#pragma mark -iOS 10 消息事件回调
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)(void))completionHandler {
  NSDictionary * userInfo = response.notification.request.content.userInfo;
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    // Apns
    NSLog(@"iOS 10 APNS 消息事件回调");
    [JPUSHService handleRemoteNotification:userInfo];
    // 保障应用被杀死状态下,用户点击推送消息,打开app后可以收到点击通知事件
    [[RCTJPushEventQueue sharedInstance]._notificationQueue insertObject:userInfo atIndex:0];
    [[NSNotificationCenter defaultCenter] postNotificationName:J_APNS_NOTIFICATION_OPENED_EVENT object:userInfo];
  }
  else {
    // 本地通知
    NSLog(@"iOS 10 本地通知 消息事件回调");
    // 保障应用被杀死状态下,用户点击推送消息,打开app后可以收到点击通知事件
    [[RCTJPushEventQueue sharedInstance]._localNotificationQueue insertObject:userInfo atIndex:0];
    [[NSNotificationCenter defaultCenter] postNotificationName:J_LOCAL_NOTIFICATION_OPENED_EVENT object:userInfo];
  }
  // 系统要求执行这个方法
  completionHandler();
}

#pragma mark - 自定义消息
- (void)networkDidReceiveMessage:(NSNotification *)notification {
  NSDictionary * userInfo = [notification userInfo];
  [[NSNotificationCenter defaultCenter] postNotificationName:J_CUSTOM_NOTIFICATION_EVENT object:userInfo];
}


#pragma mark - 清除角标
 - (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    
    [JPUSHService setBadge:0];
}

注意
开发环境测试
在对 JPush iOS 开发环境进行测试前,请确保 3 个统一:

App 是开发环境打包(开发证书 Development )
上传了开发证书并验证通过(现支持上传生产证书后勾选“将生产证书用于开发环境”,即可不用上传开发证书)

发布环境测试
在对 JPush iOS 生产环境进行测试前,请确保 3 个统一:

App 是 ad-hoc 打包或者 App Store 版本(发布证书 Production),不可使用 Xcode 直接运行。
上传了发布证书并验证通过

总结

至此,可以在极光后台发送通知测试推送消息啦

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

react-native集成极光推送 的相关文章

  • C语言学习专栏(1):易忘点

    C语言学习专栏系列 xff1a 版权申明 未经博主同意 xff0c 谢绝转载 xff01 xff08 请尊重原创 xff0c 博主保留追究权 xff09 xff1b 本博客的内容来自于 xff1a C语言学习专栏 xff08 1 xff09

随机推荐