此處我用的是jpush-react-native,這個是極光官網維護的,還有一個是react-antive-jpush,這是中文網的,我這里沒用這個
上一篇講了如何申請ios的開發和生產證書的流程,http://blog.csdn.net/liu__520/article/details/53133497
先按照官網的步驟來唄:(為了了解具體的過程,我都是用手動配置的,沒有用自動配置)
今天是2017年2月16日,現在的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
一、手動配置
1.1、進入你的項目目錄,然后打開命令終端輸入:
`npm install jpush-react-native --save`
`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 項目導進來了
使用
打開 app 下的 MainActivity,在 ReactInstanceManager 的 build 方法中加入 JPushPackage:
app/MainActivity.java
打開 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
打開 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 填寫自己的
static NSString *appKey = @"";? ? //填寫appkey
static NSString *channel = @"";? ? //填寫channel? 一般為nil
static BOOL isProduction = false;? //填寫isProdurion? 平時測試時為false ,生產時填寫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];
}
為了在收到推送點擊進入應用能夠獲取該條推送內容需要在 AppDelegate.m didReceiveRemoteNotification 方法里面添加
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo] 方法,
注意:這里需要在兩個方法里面加一個是iOS7以前的一個是iOS7即以后的,如果AppDelegate.m 沒有這個兩個方法則直接復制這兩個方法,
在 iOS10 的設備則可以使用JPush 提供的兩個方法;如下所示
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// 取得 APNs 標準信息內容
[[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); // 需要執行這個方法,選擇是否提醒用戶,有Badge、Sound、Alert三種類型可以選擇設置
}
// 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();? // 系統要求執行這個方法
}
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
具體看我以下的代碼:
/**
* 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 標準信息內容
[[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); // 需要執行這個方法,選擇是否提醒用戶,有Badge、Sound、Alert三種類型可以選擇設置
}
// 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();? // 系統要求執行這個方法
}
- (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、打開項目---capacities---打開push notifications,
1.3.5、打開項目--build settings---signing---code signing identify,都改成 ios developer,
1.3.6、然后把tests的signing也要改一下,要不然安裝到真機上會報錯的:
到此為止,配置基本就完成了,
2、下面我們在RN上進行操作了:
下面分兩部分進行:2.1、普通推送;2.2、別名推送
2.1、普通的推送
打開js文件我的是在主頁上進行的,
具體的代碼如下:
componentDidMount() {
? ? ? ? ? //---------------------------------android start---------------------------------
? ? ? ? ? JPushModule.addReceiveCustomMsgListener((message) => {
? ? ? ? ? //這是默認的通知消息
? ? ? ? //? 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);//我這里是把內容存在了數據庫里面,你可以把這里的message放到state里面顯示出來
? ? ? //這里面解析json數據,并存在數據庫中,同時顯示在通知欄上
? ? ?})
? ? ?//點擊通知進入應用的主頁,相當于跳轉到制定的頁面
? ? ?JPushModule.addReceiveOpenNotificationListener((map) => {
? ? //console.log("Opening notification!");
? ? this.props.navigator.replace({name: "HomePage",component:HomePage});
? ? })
? ? //---------------------------------android end---------------------------------
? ? //---------------------------------ios start---------------------------------
? ? ?NativeAppEventEmitter.addListener(
? ? ?'ReceiveNotification',
? ? ?(message) => {
? ? ? ? ? ? ? ? //下面就是發送過來的內容,可以用stringfy打印發來的消息
? ? ? ? ? ? ? ?console.log("content: " + JSON.stringify(message));
? ? ? ? ? ?//下面的json就是我在極光推送上的附件字段內容就是上面的log打印出來的東西
? ? ? ? // {
? ? ? ? //? ? "_j_msgid": 4572771355,?
?? ? ? //? ? "content": "日志第一天",?
?? ? ? //? ? "time": "2016-11-18/13:11:09",?
?? ? ? //? ? "aps": {
? ? ? ? ? ? ? ? ? ? ? ? ? //? ? ? ? "sound": "default",??
? ? ? ? ? ? ? ? ? ? ? ? //? ? ? ? "badge": 1,?
? ? ? ? ? ? ? ? ? ? ? //? ? ? ? "alert": "測試ios1"?
? ? ? ? ? ?//? ? },?
?? ? ? //? ? "name": "劉成",
? ? ? ? //? ? "age": "28",?
?? ? ? //? ? "性別": "男",
? ? ? ?//"qq":"674668211",
? ? ?//"手機號":"674668211",
? ? ? // } console.log("_j_msgid:" + message._j_msgid);
? ? ? ? ?//這個是極光的消息id console.log("content:" + message.content);
? ? ? ? //這是標題 console.log("aps:" + message.aps.sound);
? ? ? ? //這是聲音 console.log("aps:" + message.aps.badge);
? ? ? ? ?//這是上標 console.log("aps:" + message.aps.alert);
? ? ? ? ?//這是發送通知的主內容 this.storeDB(message); } );
? ? ? ?//---------------------------------ios end---------------------------------
}
//最后在組件卸載的時間取消監聽:
componentWillUnmount() {
? ? ? ?JPushModule.removeReceiveCustomMsgListener();
? ? ? JPushModule.removeReceiveNotificationListener();
? ? ? BackAndroid.removeEventListener('hardwareBackPress');
? ? ? NativeAppEventEmitter.removeAllListeners();
? ? ?DeviceEventEmitter.removeAllListeners();
? }
上面的android的推送內容都在message.content里面,附加的數據在message.extras,
message就是發送過來的消息內容:addReceiveNotificationListener
如果你沒有附加的消息,只是顯示消息內容,用這個方法就行了:addReceiveCustomMsgListener
如果你要點擊通知打開某個應用,用:addReceiveOpenNotificationListener
ios的要用到注冊監聽事件:
NativeAppEventEmitter.addListener
消息內容都在message里面,可以看下我的示例,結合我極光推送的附加字段:就會明白的//我這里是把內容存在了數據庫里面,
你可以把這里的message
放到state里面顯示出來
2.2、別名推送
setAlias有三個參數,第一個是你要推送的別名,要注冊到極光的,第二和第三個分別是設置成功的回調、設置失敗的回調
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) => {
? ? //這是默認的通知消息
? ? // console.log(message)
? ? });
? ? JPushModule.addReceiveNotificationListener((map) => {
? ? //? var message = JSON.parse(map.extras);
? ? });
? ? //點擊通知進入應用的主頁
? ? JPushModule.addReceiveOpenNotificationListener((map) => ? ? ? {})
? ? //---------------------------------android end---------------------------------
? ? }
? ?fail=()=>{
? ?}