React-Native极光推送全程教程android和ios

来源:互联网 发布:sqlserver generator 编辑:程序博客网 时间:2024/05/17 08:01

 坑爹的坑,终于把极光推送的全套跑通了,Android和iOS平台全部测试成功!下面就目前遇到的问题做详细的说明,希望能给大家引上正确的道路大哭。http://blog.csdn.net/liu__520/article/details/53133441

此处我用的是jpush-react-native,这个是极光官网维护的,还有一个是react-antive-jpush,这是中文网的,我这里没用这个

上一篇讲了如何申请ios的开发和生产证书的流程,http://blog.csdn.net/liu__520/article/details/53133497

先按照官网的步骤来呗:(为了了解具体的过程,我都是用手动配置的,没有用自动配置)

一、手动配置

1.1、进入你的项目目录,然后打开命令终端输入:

[plain] view plain copy
  1. npm install jpush-react-native --save  
  2. rnpm link jpush-react-native  
1.2、android版的具体配置:

使用 android Studio import 你的 React Native 应用(选择你的 react Native 应用所在目录下的 android 文件夹即可)

修改 android 项目下的 settings.gradle 配置:

打开setting.gradle,然后添加如下代码:

include ':app', ':jpush-react-native'

project(':jpush-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/jpush-react-native/android')

修改app 下的 AndroidManifest 配置,将 jpush 相关的配置复制到这个文件中,参考 demo 的 AndroidManifest:(增加了 部分)

你的 React Native project/android/app/AndroidManifest.xml

android:name=".MainApplication"

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme">

android:name=".MainActivity"

android:configChanges="keyboard|keyboardHidden|orientation|screenSize"

android:label="@string/app_name">

修改 app 下的 build.gradle 配置:

your react native project/android/app/build.gradle

android {    defaultConfig {        applicationId "yourApplicationId"        ...manifestPlaceholders = [

JPUSH_APPKEY: "yourAppKey", //在此替换你的APPKey

APP_CHANNEL: "developer-default"    //应用渠道号,默认就好

]}}...dependencies {    compile fileTree(dir: "libs", include: ["*.jar"])compile project(':jpush-react-native')compile "com.facebook.react:react-native:+"  // From node_modules}

将此处的 yourApplicationId 替换为你的项目的包名;yourAppKey 替换成你在官网上申请的应用的 AppKey。到此为止,配置完成。

现在重新 sync 一下项目,应该能看到 jpush-react-native 作为一个 android Library 项目导进来了

使用RN 0.29.0 以下版本

打开 app 下的 MainActivity,在 ReactInstanceManager 的 build 方法中加入 JPushPackage:

app/MainActivity.Java


RN 0.29.0 以上版本

打开 app 下的 MainApplication.java 文件,然后加入 JPushPackage,参考 demo:

[plain] view plain copy
  1. app/MainApplication.java  
  2.   
  3. private boolean SHUTDOWN_TOAST = false;  
  4.   
  5. private boolean SHUTDOWN_LOG = false;  
  6.   
  7. private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {  
  8.   
  9. @Override  
  10.   
  11. protected boolean getUseDeveloperSupport() {  
  12.   
  13. return BuildConfig.DEBUG;  
  14.   
  15. }  
  16.   
  17. @Override  
  18.   
  19. protected List getPackages() {  
  20.   
  21. return Arrays.asList(  
  22.   
  23. new MainReactPackage(),  
  24.   
  25. new JPushPackage(SHUTDOWN_TOAST, SHUTDOWN_LOG)  
  26.   
  27. );  
  28.   
  29. }  
  30.   
  31. };  

1.3、ios配置

ios Usage

打开 iOS 工程,在 rnpm link 之后,RCTJPushModule.xcodeproj 工程会自动添加到 Libraries 目录里面

在 iOS 工程 target 的 Build Phases->Link Binary with Libraries 中加入如下库

libz.tbd

CoreTelephony.framework

Security.framework

CFNetwork.framework

CoreFoundation.framework

SystemConfiguration.framework

Foundation.framework

UIKit.framework

UserNotifications.framework

libresolv.tbd

在 AppDelegate.h 文件中 填写如下代码,这里的的 appkey、channel、和 isProduction 填写自己的

[plain] view plain copy
  1. static NSString *appKey = @"";    //填写appkey  
  2.   
  3. static NSString *channel = @"";    //填写channel  一般为nil  
  4.   
  5. static BOOL isProduction = false;  //填写isProdurion  平时测试时为false ,生产时填写true  
  6.   
  7. 在AppDelegate.m 的didFinishLaunchingWithOptions 方法里面添加如下代码  
  8.   
  9. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  10.   
  11. {  
  12.   
  13. if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {  
  14.   
  15. //可以添加自定义categories  
  16.   
  17. [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |  
  18.   
  19. UIUserNotificationTypeSound |  
  20.   
  21. UIUserNotificationTypeAlert)  
  22.   
  23. categories:nil];  
  24.   
  25. } else {  
  26.   
  27. //iOS 8以前 categories 必须为nil  
  28.   
  29. [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |  
  30.   
  31. UIRemoteNotificationTypeSound |  
  32.   
  33. UIRemoteNotificationTypeAlert)  
  34.   
  35. categories:nil];  
  36.   
  37. }  
  38.   
  39. [JPUSHService setupWithOption:launchOptions appKey:appKey  
  40.   
  41. channel:channel apsForProduction:isProduction];  
  42.   
  43. }  
  44.   
  45. 在AppDelegate.m 的didRegisterForRemoteNotificationsWithDeviceToken 方法中添加 [JPUSHService registerDeviceToken:deviceToken]; 如下所示  
  46.   
  47. - (void)application:(UIApplication *)application  
  48.   
  49. didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {  
  50.   
  51. [JPUSHService registerDeviceToken:deviceToken];  
  52.   
  53. }  
  54.   
  55. 为了在收到推送点击进入应用能够获取该条推送内容需要在 AppDelegate.m didReceiveRemoteNotification 方法里面添加  
  56.   
  57. [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo] 方法,  
  58.   
  59. 注意:这里需要在两个方法里面加一个是iOS7以前的一个是iOS7即以后的,如果AppDelegate.m 没有这个两个方法则直接复制这两个方法,  
  60.   
  61. 在 iOS10 的设备则可以使用JPush 提供的两个方法;如下所示  
  62.   
  63. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {  
  64.   
  65. // 取得 APNs 标准信息内容  
  66.   
  67. [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];  
  68.   
  69. }  
  70. //iOS 7 Remote Notification  
  71.   
  72. - (void)application:(UIApplication *)application didReceiveRemoteNotification:  (NSDictionary *)userInfo fetchCompletionHandler:(void (^)  (UIBackgroundFetchResult))completionHandler {  
  73.   
  74. [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];  
  75.   
  76. }  
  77. // iOS 10 Support  
  78.   
  79. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {  
  80.   
  81. // Required  
  82.   
  83. NSDictionary * userInfo = notification.request.content.userInfo;  
  84.   
  85. if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {  
  86.   
  87. [JPUSHService handleRemoteNotification:userInfo];  
  88.   
  89. [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];  
  90.   
  91. }  
  92.   
  93. completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置  
  94.   
  95. }  
  96.   
  97. // iOS 10 Support  
  98.   
  99. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {  
  100.   
  101. // Required  
  102.   
  103. NSDictionary * userInfo = response.notification.request.content.userInfo;  
  104.   
  105. if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {  
  106.   
  107. [JPUSHService handleRemoteNotification:userInfo];  
  108.   
  109. [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];  
  110.   
  111. }  
  112.   
  113. completionHandler();  // 系统要求执行这个方法  
  114.   
  115. }  

1.3.1、下面直接放我的代码图吧,上面的代码都是官网的,但是有几个地方是需要修改的,也是需要增加的,要不然各种报错,:





1.3.2、还有一个最重要的,把github上极光的代码都放到你的这个AppDelegate.m文件中,然后加一个接口

@interfaceAppDelegate();

而且用官网的代码会提示下面的警告信息:

/Users/vittorio/Desktop/log/ios/log/AppDelegate.m:39:55: 'UIRemoteNotificationTypeBadge' is deprecated:

first deprecated in iOS 8.0 - Use UserNotifications Framework's UNAuthorizationOptions for user notifications

and registerForRemoteNotifications for receiving remote notifications instead.

需要把代码里面的UIRemoteNotificationType改成:UNAuthorizationOption

具体看我以下的代码:

[plain] view plain copy
  1. /**  
  2.   
  3. * Copyright (c) 2015-present, Facebook, Inc.  
  4.   
  5. * All rights reserved.  
  6.   
  7. *  
  8.   
  9. * This source code is licensed under the BSD-style license found in the  
  10.   
  11. * LICENSE file in the root directory of this source tree. An additional grant  
  12.   
  13. * of patent rights can be found in the PATENTS file in the same directory.  
  14.   
  15. */  
  16.   
  17. #import "AppDelegate.h"  
  18.   
  19. #import "RCTBundleURLProvider.h"  
  20.   
  21. #import "RCTRootView.h"  
  22.   
  23. // ---------------------------start极光推送--------------------------  
  24.   
  25. #import "JPUSHService.h"  
  26.   
  27. #import  
  28.   
  29. #import  
  30.   
  31. #ifdef NSFoundationVersionNumber_iOS_9_x_Max  
  32.   
  33. #import  
  34.   
  35. #endif  
  36.   
  37. @interface AppDelegate ()  
  38.   
  39. // ---------------------------end极光推送---------------------------  
  40.   
  41. @end  
  42.   
  43. @implementation AppDelegate  
  44.   
  45. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  46.   
  47. {  
  48.   
  49. // ---------------------------start极光推送--------------------------  
  50.   
  51. //Required  
  52.   
  53. if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {  
  54.   
  55. JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];  
  56.   
  57. entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;  
  58.   
  59. [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];  
  60.   
  61. }  
  62.   
  63. else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {  
  64.   
  65. //可以添加自定义categories  
  66.   
  67. [JPUSHService registerForRemoteNotificationTypes:(UNAuthorizationOptionBadge |  
  68.   
  69. UNAuthorizationOptionSound |  
  70.   
  71. UNAuthorizationOptionAlert)  
  72.   
  73. categories:nil];  
  74.   
  75. }  
  76.   
  77. else {  
  78.   
  79. //categories 必须为nil  
  80.   
  81. [JPUSHService registerForRemoteNotificationTypes:(UNAuthorizationOptionBadge |  
  82.   
  83. UNAuthorizationOptionSound |  
  84.   
  85. UNAuthorizationOptionAlert)  
  86.   
  87. categories:nil];  
  88.   
  89. }  
  90.   
  91. [JPUSHService setupWithOption:launchOptions appKey:appKey  
  92.   
  93. channel:nil apsForProduction:nil];  
  94.   
  95. // ---------------------------end极光推送--------------------------  
  96.   
  97. NSURL *jsCodeLocation;  
  98.   
  99. jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];  
  100.   
  101. RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation  
  102.   
  103. moduleName:@"log"  
  104.   
  105. initialProperties:nil  
  106.   
  107. launchOptions:launchOptions];  
  108.   
  109. rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];  
  110.   
  111. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];  
  112.   
  113. UIViewController *rootViewController = [UIViewController new];  
  114.   
  115. rootViewController.view = rootView;  
  116.   
  117. self.window.rootViewController = rootViewController;  
  118.   
  119. [self.window makeKeyAndVisible];  
  120.   
  121. return YES;  
  122.   
  123. }  
  124.   
  125. // ---------------------------start极光推送--------------------------  
  126.   
  127. //-----------------------------------------------------------------------  
  128.   
  129. - (void)application:(UIApplication *)application  
  130.   
  131. didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {  
  132.   
  133. [JPUSHService registerDeviceToken:deviceToken];  
  134.   
  135. }  
  136.   
  137. //-----------------------------------------------------------------------  
  138.   
  139. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {  
  140.   
  141. // 取得 APNs 标准信息内容  
  142.   
  143. [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];  
  144.   
  145. }  
  146.   
  147. //iOS 7 Remote Notification  
  148.   
  149. - (void)application:(UIApplication *)application didReceiveRemoteNotification:  (NSDictionary *)userInfo fetchCompletionHandler:(void (^)  (UIBackgroundFetchResult))completionHandler {  
  150.   
  151. [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];  
  152.   
  153. }  
  154.   
  155. // iOS 10 Support  
  156.   
  157. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {  
  158.   
  159. // Required  
  160.   
  161. NSDictionary * userInfo = notification.request.content.userInfo;  
  162.   
  163. if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {  
  164.   
  165. [JPUSHService handleRemoteNotification:userInfo];  
  166.   
  167. [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];  
  168.   
  169. }  
  170.   
  171. completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置  
  172.   
  173. }  
  174.   
  175. // iOS 10 Support  
  176.   
  177. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {  
  178.   
  179. // Required  
  180.   
  181. NSDictionary * userInfo = response.notification.request.content.userInfo;  
  182.   
  183. if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {  
  184.   
  185. [JPUSHService handleRemoteNotification:userInfo];  
  186.   
  187. [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];  
  188.   
  189. }  
  190.   
  191. completionHandler();  // 系统要求执行这个方法  
  192.   
  193. }  
  194.   
  195. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {  
  196.   
  197. //Optional  
  198.   
  199. NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);  
  200.   
  201. }  
  202.   
  203. // ---------------------------end极光推送--------------------------  
  204.   
  205. @end  

1.3.3、然后需要选择描述配置的东西吧:

具体看下面的两张图:




1.3.4、打开项目---capacities---打开push notifications,



1.3.5、打开项目--build settings---signing---code signing identify,都改成 ios developer,



1.3.6、然后把tests的signing也要改一下,要不然安装到真机上会报错的:



到此为止,配置基本就完成了,

2、下面我们在RN上进行操作了:

打开js文件我的是在主页上进行的,

具体的代码如下:

[plain] view plain copy
  1. componentDidMount() {  
  2.   
  3. //---------------------------------android start---------------------------------  
  4.   
  5. JPushModule.addReceiveCustomMsgListener((message) => {  
  6.   
  7. //这是默认的通知消息  
  8.   
  9. //  this.setState({pushMsg:message});  
  10.   
  11. });  
  12.   
  13. JPushModule.addReceiveNotificationListener((map) => {  
  14.   
  15. //自定义推送的消息  
  16.   
  17. //console.log("alertContent: " + map.alertContent);  
  18.   
  19. //extra是可选配置上的附件字段  
  20.   
  21. //console.log("extras: " + map.extras);  
  22.   
  23. var message = JSON.parse(map.extras);  
  24.   
  25. this.storeDB(message);//我这里是把内容存在了数据库里面,你可以把这里的message放到state里面显示出来  
  26.   
  27. //这里面解析json数据,并存在数据库中,同时显示在通知栏上  
  28.   
  29. })  
  30.   
  31. //点击通知进入应用的主页,相当于跳转到制定的页面  
  32.   
  33. JPushModule.addReceiveOpenNotificationListener((map) => {  
  34.   
  35. //console.log("Opening notification!");  
  36.   
  37. this.props.navigator.replace({name: "HomePage",component:HomePage});  
  38.   
  39. })  
  40.   
  41. //---------------------------------android end---------------------------------  
  42.   
  43. //---------------------------------ios start---------------------------------  
  44.   
  45. NativeAppEventEmitter.addListener(  
  46.   
  47. 'ReceiveNotification',  
  48.   
  49. (message) => {  
  50.   
  51. //下面就是发送过来的内容,可以用stringfy打印发来的消息  
  52.   
  53. console.log("content: " + JSON.stringify(message));  
  54.   
  55. //下面的json就是我在极光推送上的附件字段内容就是上面的log打印出来的东西  
  56.   
  57.         // {  
  58.   
  59.         //    "_j_msgid": 4572771355,   
  60.   
  61.        //    "content": "日志第一天",   
  62.   
  63.        //    "time": "2016-11-18/13:11:09",   
  64.   
  65.        //    "aps": {  
  66.   
  67.                           //        "sound": "default",    
  68.   
  69.                         //        "badge": 1,   
  70.   
  71.                       //        "alert": "测试ios1"   
  72.   
  73.            //    },   
  74.   
  75.        //    "name": "刘成",  
  76.   
  77.         //    "age": "28",   
  78.   
  79.        //    "性别": "男",  
  80.   
  81.        //"qq":"674668211",  
  82.   
  83.      //"手机号":"674668211",  
  84.   
  85. // } console.log("_j_msgid:" + message._j_msgid);  
  86.   
  87. //这个是极光的消息id console.log("content:" + message.content);  
  88.   
  89. //这是标题 console.log("aps:" + message.aps.sound);  
  90.   
  91. //这是声音 console.log("aps:" + message.aps.badge);  
  92.   
  93. //这是上标 console.log("aps:" + message.aps.alert);  
  94.   
  95. //这是发送通知的主内容 this.storeDB(message); } );  
  96.   
  97. //---------------------------------ios end---------------------------------  
  98.   
  99. }  
  100.   
  101. //最后在组件卸载的时间取消监听:  
  102.   
  103. componentWillUnmount() {  
  104.   
  105. JPushModule.removeReceiveCustomMsgListener();  
  106.   
  107. JPushModule.removeReceiveNotificationListener();  
  108.   
  109. BackAndroid.removeEventListener('hardwareBackPress');  
  110.   
  111. NativeAppEventEmitter.removeAllListeners();  
  112.   
  113. DeviceEventEmitter.removeAllListeners();  
  114.   
  115. }  

上面的android的推送内容都在message.content里面,附加的数据在message.extras,

message就是发送过来的消息内容:addReceiveNotificationListener

如果你没有附加的消息,只是显示消息内容,用这个方法就行了:addReceiveCustomMsgListener

如果你要点击通知打开某个应用,用:addReceiveOpenNotificationListener

ios的要用到注册监听事件:

NativeAppEventEmitter.addListener

消息内容都在message里面,可以看下我的示例,结合我极光推送的附加字段:就会明白的//我这里是把内容存在了数据库里面,

你可以把这里的message

放到state里面显示出来

3、最后给大家看下我的极光推送的内容吧:












[javascript] view plain copy
  1. <pre></pre>  
  2. <pre></pre>  
  3. <pre></pre>