此處我用的是jpush-react-native辰企,這個(gè)是極光官網(wǎng)維護(hù)的风纠,還有一個(gè)是react-antive-jpush,這是中文網(wǎng)的牢贸,我這里沒(méi)用這個(gè)
先按照官網(wǎng)的步驟來(lái)唄:(為了了解具體的過(guò)程,我都是用手動(dòng)配置的,沒(méi)有用自動(dòng)配置)
今天是2017年2月16日臭增,現(xiàn)在的RN版本是0.41.2懂酱,
for latest RN, use latest
for RN < 0.40.0, use v1.3.6
for jpush-react-native > 1.4.4, need install jcore-react-native
如果你的RN版本小于0.40.0,用極光的1.3.6版本速址;
如果>=0.40.0,就要用最新的玩焰;
而且如果jpush-react-native > 1.4.4由驹,需要用到jcore-react-native
一芍锚、手動(dòng)配置
1.1、進(jìn)入你的項(xiàng)目目錄蔓榄,然后打開(kāi)命令終端輸入:
`npm install jpush-react-native --save`
`rnpm link jpush-react-native`
1.2并炮、android版的具體配置:
使用 Android Studio import 你的 React Native 應(yīng)用(選擇你的 React Native 應(yīng)用所在目錄下的 android 文件夾即可)
修改 android 項(xiàng)目下的 settings.gradle 配置:
打開(kāi)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 相關(guān)的配置復(fù)制到這個(gè)文件中逃魄,參考 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"? ? //應(yīng)用渠道號(hào),默認(rèn)就好
? ? ? ? ? ? ? ? ? ]
? ? ? ? ? ?}
?}
...
dependencies {
? ? compile fileTree(dir: "libs", include: ["*.jar"])
? ? ?compile project(':jpush-react-native')
? ? compile "com.facebook.react:react-native:+"? // From node_modules
?}
將此處的 yourApplicationId 替換為你的項(xiàng)目的包名澜搅;yourAppKey 替換成你在官網(wǎng)上申請(qǐng)的應(yīng)用的 AppKey伍俘。到此為止,配置完成勉躺。
現(xiàn)在重新 sync 一下項(xiàng)目癌瘾,應(yīng)該能看到 jpush-react-native 作為一個(gè) android Library 項(xiàng)目導(dǎo)進(jìn)來(lái)了
使用
打開(kāi) app 下的 MainActivity,在 ReactInstanceManager 的 build 方法中加入 JPushPackage:
app/MainActivity.java
打開(kāi) app 下的 MainApplication.java 文件饵溅,然后加入 JPushPackage妨退,參考 demo:
app/MainApplication.java
private boolean SHUTDOWN_TOAST = false;
private boolean SHUTDOWN_LOG = false;
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
? ? ? ? ?@Override
? ? ? ? ?protected boolean getUseDeveloperSupport() {
? ? ? ? ? ? ? return BuildConfig.DEBUG;
? ? ? ? ? }
? ? ? ? @Override
? ? ? ? protected List getPackages() {
? ? ? ? ? ? ? ? return Arrays.asList(
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? new MainReactPackage(),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?new JPushPackage(SHUTDOWN_TOAST, SHUTDOWN_LOG)
? ? ? ? ? ? ? ? ? ?);
? ? ? ? ? ? ?}
? ? ?};
1.3、ios配置
iOS Usage
打開(kāi) iOS 工程蜕企,在 rnpm link 之后咬荷,RCTJPushModule.xcodeproj 工程會(huì)自動(dòng)添加到 Libraries 目錄里面
在 iOS 工程 target 的 Build Phases->Link Binary with Libraries 中加入如下庫(kù)
libz.tbd
CoreTelephony.framework
Security.framework
CFNetwork.framework
CoreFoundation.framework
SystemConfiguration.framework
Foundation.framework
UIKit.framework
UserNotifications.framework
libresolv.tbd
在 AppDelegate.h 文件中 填寫(xiě)如下代碼,這里的的 appkey轻掩、channel幸乒、和 isProduction 填寫(xiě)自己的
static NSString *appKey = @"";? ? //填寫(xiě)appkey
static NSString *channel = @"";? ? //填寫(xiě)channel? 一般為nil
static BOOL isProduction = false;? //填寫(xiě)isProdurion? 平時(shí)測(cè)試時(shí)為false ,生產(chǎn)時(shí)填寫(xiě)true
在AppDelegate.m 的didFinishLaunchingWithOptions 方法里面添加如下代碼
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//可以添加自定義categories
[JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
UIUserNotificationTypeSound |
UIUserNotificationTypeAlert)
categories:nil];
} else {
//iOS 8以前 categories 必須為nil
[JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert)
categories:nil];
}
[JPUSHService setupWithOption:launchOptions appKey:appKey
channel:channel apsForProduction:isProduction];
}
在AppDelegate.m 的didRegisterForRemoteNotificationsWithDeviceToken 方法中添加 [JPUSHService registerDeviceToken:deviceToken]; 如下所示
- (void)application:(UIApplication *)application
? ? ? ? didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
? ? ? ? [JPUSHService registerDeviceToken:deviceToken];
}
為了在收到推送點(diǎn)擊進(jìn)入應(yīng)用能夠獲取該條推送內(nèi)容需要在 AppDelegate.m didReceiveRemoteNotification 方法里面添加
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo] 方法唇牧,
注意:這里需要在兩個(gè)方法里面加一個(gè)是iOS7以前的一個(gè)是iOS7即以后的罕扎,如果AppDelegate.m 沒(méi)有這個(gè)兩個(gè)方法則直接復(fù)制這兩個(gè)方法,
在 iOS10 的設(shè)備則可以使用JPush 提供的兩個(gè)方法奋构;如下所示
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// 取得 APNs 標(biāo)準(zhǔn)信息內(nèi)容
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
}
//iOS 7 Remote Notification
- (void)application:(UIApplication *)application didReceiveRemoteNotification:? (NSDictionary *)userInfo fetchCompletionHandler:(void (^)? (UIBackgroundFetchResult))completionHandler {
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
}
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
? ? ? // Required
? ? ? ?NSDictionary * userInfo = notification.request.content.userInfo;
? ? ? ? if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
? ? ? ?[JPUSHService handleRemoteNotification:userInfo];
? ? ? [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
? ? ? ? }
completionHandler(UNNotificationPresentationOptionAlert); // 需要執(zhí)行這個(gè)方法壳影,選擇是否提醒用戶,有Badge弥臼、Sound宴咧、Alert三種類(lèi)型可以選擇設(shè)置
}
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
// Required
? ? ? ? NSDictionary * userInfo = response.notification.request.content.userInfo;
? ? ? ? if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
? ? ? ? [JPUSHService handleRemoteNotification:userInfo];
? ? ? ?[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
? ? ?}
completionHandler();? // 系統(tǒng)要求執(zhí)行這個(gè)方法
}
1.3.1、下面直接放我的代碼圖吧径缅,上面的代碼都是官網(wǎng)的掺栅,但是有幾個(gè)地方是需要修改的烙肺,也是需要增加的,要不然各種報(bào)錯(cuò)氧卧,:
1.3.2桃笙、還有一個(gè)最重要的,把github上極光的代碼都放到你的這個(gè)AppDelegate.m文件中沙绝,然后加一個(gè)接口
@interfaceAppDelegate()搏明;
而且用官網(wǎng)的代碼會(huì)提示下面的警告信息:
/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
具體看我以下的代碼:
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import "AppDelegate.h"
#import "RCTBundleURLProvider.h"
#import "RCTRootView.h"
// ---------------------------start極光推送--------------------------
#import "JPUSHService.h"
#import
#import
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import
#endif
@interface AppDelegate ()
// ---------------------------end極光推送---------------------------
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// ---------------------------start極光推送--------------------------
//Required
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
[JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
}
else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//可以添加自定義categories
[JPUSHService registerForRemoteNotificationTypes:(UNAuthorizationOptionBadge |
UNAuthorizationOptionSound |
UNAuthorizationOptionAlert)
categories:nil];
}
else {
//categories 必須為nil
[JPUSHService registerForRemoteNotificationTypes:(UNAuthorizationOptionBadge |
UNAuthorizationOptionSound |
UNAuthorizationOptionAlert)
categories:nil];
}
[JPUSHService setupWithOption:launchOptions appKey:appKey
channel:nil apsForProduction:nil];
// ---------------------------end極光推送--------------------------
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"log"
initialProperties:nil
launchOptions:launchOptions];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
return YES;
}
// ---------------------------start極光推送--------------------------
//-----------------------------------------------------------------------
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[JPUSHService registerDeviceToken:deviceToken];
}
//-----------------------------------------------------------------------
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// 取得 APNs 標(biāo)準(zhǔn)信息內(nèi)容
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
}
//iOS 7 Remote Notification
- (void)application:(UIApplication *)application didReceiveRemoteNotification:? (NSDictionary *)userInfo fetchCompletionHandler:(void (^)? (UIBackgroundFetchResult))completionHandler {
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
}
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
// Required
NSDictionary * userInfo = notification.request.content.userInfo;
if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
}
completionHandler(UNNotificationPresentationOptionAlert); // 需要執(zhí)行這個(gè)方法,選擇是否提醒用戶闪檬,有Badge星著、Sound、Alert三種類(lèi)型可以選擇設(shè)置
}
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
// Required
NSDictionary * userInfo = response.notification.request.content.userInfo;
if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
}
completionHandler();? // 系統(tǒng)要求執(zhí)行這個(gè)方法
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
//Optional
NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
// ---------------------------end極光推送--------------------------
@end
1.3.3粗悯、然后需要選擇描述配置的東西吧:
具體看下面的兩張圖:
1.3.4虚循、打開(kāi)項(xiàng)目---capacities---打開(kāi)push notifications,
1.3.5、打開(kāi)項(xiàng)目--build settings---signing---code signing identify,都改成 ios developer样傍,
1.3.6横缔、然后把tests的signing也要改一下,要不然安裝到真機(jī)上會(huì)報(bào)錯(cuò)的:
到此為止衫哥,配置基本就完成了茎刚,
2、下面我們?cè)赗N上進(jìn)行操作了:
下面分兩部分進(jìn)行:2.1炕檩、普通推送斗蒋;2.2、別名推送
2.1笛质、普通的推送
打開(kāi)js文件我的是在主頁(yè)上進(jìn)行的泉沾,
具體的代碼如下:
componentDidMount() {
? ? ? ? ? //---------------------------------android start---------------------------------
? ? ? ? ? JPushModule.addReceiveCustomMsgListener((message) => {
? ? ? ? ? //這是默認(rèn)的通知消息
? ? ? ? //? this.setState({pushMsg:message});
? ? ? ? });
? ? ? ?JPushModule.addReceiveNotificationListener((map) => {
? ? ? //自定義推送的消息
? ? ? ?//console.log("alertContent: " + map.alertContent);
? ? ?//extra是可選配置上的附件字段
? ? ?//console.log("extras: " + map.extras);
? ? ?var message = JSON.parse(map.extras);
? ? ? ?this.storeDB(message);//我這里是把內(nèi)容存在了數(shù)據(jù)庫(kù)里面,你可以把這里的message放到state里面顯示出來(lái)
? ? ? //這里面解析json數(shù)據(jù)妇押,并存在數(shù)據(jù)庫(kù)中跷究,同時(shí)顯示在通知欄上
? ? ?})
? ? ?//點(diǎn)擊通知進(jìn)入應(yīng)用的主頁(yè),相當(dāng)于跳轉(zhuǎn)到制定的頁(yè)面
? ? ?JPushModule.addReceiveOpenNotificationListener((map) => {
? ? //console.log("Opening notification!");
? ? this.props.navigator.replace({name: "HomePage",component:HomePage});
? ? })
? ? //---------------------------------android end---------------------------------
? ? //---------------------------------ios start---------------------------------
? ? ?NativeAppEventEmitter.addListener(
? ? ?'ReceiveNotification',
? ? ?(message) => {
? ? ? ? ? ? ? ? //下面就是發(fā)送過(guò)來(lái)的內(nèi)容敲霍,可以用stringfy打印發(fā)來(lái)的消息
? ? ? ? ? ? ? ?console.log("content: " + JSON.stringify(message));
? ? ? ? ? ?//下面的json就是我在極光推送上的附件字段內(nèi)容就是上面的log打印出來(lái)的東西
? ? ? ? // {
? ? ? ? //? ? "_j_msgid": 4572771355,?
?? ? ? //? ? "content": "日志第一天",?
?? ? ? //? ? "time": "2016-11-18/13:11:09",?
?? ? ? //? ? "aps": {
? ? ? ? ? ? ? ? ? ? ? ? ? //? ? ? ? "sound": "default",??
? ? ? ? ? ? ? ? ? ? ? ? //? ? ? ? "badge": 1,?
? ? ? ? ? ? ? ? ? ? ? //? ? ? ? "alert": "測(cè)試ios1"?
? ? ? ? ? ?//? ? },?
?? ? ? //? ? "name": "劉成",
? ? ? ? //? ? "age": "28",?
?? ? ? //? ? "性別": "男",
? ? ? ?//"qq":"674668211"俊马,
? ? ?//"手機(jī)號(hào)":"674668211",
? ? ? // } console.log("_j_msgid:" + message._j_msgid);
? ? ? ? ?//這個(gè)是極光的消息id console.log("content:" + message.content);
? ? ? ? //這是標(biāo)題 console.log("aps:" + message.aps.sound);
? ? ? ? //這是聲音 console.log("aps:" + message.aps.badge);
? ? ? ? ?//這是上標(biāo) console.log("aps:" + message.aps.alert);
? ? ? ? ?//這是發(fā)送通知的主內(nèi)容 this.storeDB(message); } );
? ? ? ?//---------------------------------ios end---------------------------------
}
//最后在組件卸載的時(shí)間取消監(jiān)聽(tīng):
componentWillUnmount() {
? ? ? ?JPushModule.removeReceiveCustomMsgListener();
? ? ? JPushModule.removeReceiveNotificationListener();
? ? ? BackAndroid.removeEventListener('hardwareBackPress');
? ? ? NativeAppEventEmitter.removeAllListeners();
? ? ?DeviceEventEmitter.removeAllListeners();
? }
上面的android的推送內(nèi)容都在message.content里面肩杈,附加的數(shù)據(jù)在message.extras,
message就是發(fā)送過(guò)來(lái)的消息內(nèi)容:addReceiveNotificationListener
如果你沒(méi)有附加的消息柴我,只是顯示消息內(nèi)容,用這個(gè)方法就行了:addReceiveCustomMsgListener
如果你要點(diǎn)擊通知打開(kāi)某個(gè)應(yīng)用扩然,用:addReceiveOpenNotificationListener
ios的要用到注冊(cè)監(jiān)聽(tīng)事件:
NativeAppEventEmitter.addListener
消息內(nèi)容都在message里面艘儒,可以看下我的示例,結(jié)合我極光推送的附加字段:就會(huì)明白的//我這里是把內(nèi)容存在了數(shù)據(jù)庫(kù)里面,
你可以把這里的message
放到state里面顯示出來(lái)
2.2界睁、別名推送
setAlias有三個(gè)參數(shù)觉增,第一個(gè)是你要推送的別名,要注冊(cè)到極光的翻斟,第二和第三個(gè)分別是設(shè)置成功的回調(diào)逾礁、設(shè)置失敗的回調(diào)
import JPushModule from 'jpush-react-native';
'您的別名' !== '' ? (JPushModule.setAlias('您的別名',this.success,this.fail)):null
success=()=>{
? ? NativeAppEventEmitter.addListener( 'ReceiveNotification', (message) => {JPushModule.setBadge(0,function(){
? ? // console.log(message)
? ? })} );
? //---------------------------------android start---------------------------------
? ? JPushModule.addReceiveCustomMsgListener((message) => {
? ? //這是默認(rèn)的通知消息
? ? // console.log(message)
? ? });
? ? JPushModule.addReceiveNotificationListener((map) => {
? ? //? var message = JSON.parse(map.extras);
? ? });
? ? //點(diǎn)擊通知進(jìn)入應(yīng)用的主頁(yè)
? ? JPushModule.addReceiveOpenNotificationListener((map) => ? ? ? {})
? ? //---------------------------------android end---------------------------------
? ? }
? ?fail=()=>{
? ?}