react native極光推送全程教程android和ios

此處我用的是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 項目導進來了

使用

RN 0.29.0 以下版本


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

app/MainActivity.java

RN 0.29.0 以上版本


打開 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=()=>{

? ?}

總的來說

3、最后給大家看下我的極光推送的內容吧:


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,702評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,143評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,553評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,620評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,416評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,940評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,024評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,170評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,709評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,597評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,784評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,291評論 5 357
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,029評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,407評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,663評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,403評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,746評論 2 370

推薦閱讀更多精彩內容