README.md 17.8 KB
Newer Older
Libin Lu's avatar
Libin Lu committed
1 2
[![Join the chat at https://gitter.im/evollu/react-native-fcm](https://badges.gitter.im/evollu/react-native-fcm.svg)](https://gitter.im/evollu/react-native-fcm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Libin Lu's avatar
Libin Lu committed
3 4 5
## NOTE: 
- If you are running RN < 0.30.0, you need to use react-native-fcm@1.0.15
- If you are running RN < 0.33.0, you need to user react-native-fcm@1.1.0
Libin Lu's avatar
Libin Lu committed
6
- Otherwise use latest v2
Libin Lu's avatar
Libin Lu committed
7

Libin Lu's avatar
init  
Libin Lu committed
8 9 10
## Installation

- Run `npm install react-native-fcm --save`
11
- Run `react-native link react-native-fcm` (RN 0.29.1+, otherwise `rnpm link react-native-fcm`)
Libin Lu's avatar
init  
Libin Lu committed
12

13
## Android Configuration
Libin Lu's avatar
init  
Libin Lu committed
14

15 16 17 18 19
- Edit `android/build.gradle`:
```diff
  dependencies {
    classpath 'com.android.tools.build:gradle:2.0.0'
+   classpath 'com.google.gms:google-services:3.0.0'
Libin Lu's avatar
init  
Libin Lu committed
20 21
```

22 23 24 25
- Edit `android/app/build.gradle`:
```diff
  apply plugin: "com.android.application"
+ apply plugin: 'com.google.gms.google-services'
Libin Lu's avatar
init  
Libin Lu committed
26 27
```

28
- Edit `android/app/src/main/AndroidManifest.xml`:
Libin Lu's avatar
init  
Libin Lu committed
29

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
```diff
  <application
    ...
    android:theme="@style/AppTheme">

+   <service android:name="com.evollu.react.fcm.MessagingService">
+     <intent-filter>
+       <action android:name="com.google.firebase.MESSAGING_EVENT"/>
+     </intent-filter>
+   </service>

+   <service android:name="com.evollu.react.fcm.InstanceIdService" android:exported="false">
+     <intent-filter>
+       <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
+     </intent-filter>
+   </service>

    ...
Libin Lu's avatar
init  
Libin Lu committed
48
```
49

50
### Config for notification and `click_action` in Android
51 52 53 54 55 56 57 58 59 60 61 62 63

To allow android to respond to `click_action`, you need to define Activities and filter on specific intent. Since all javascript is running in MainActivity, you can have MainActivity to handle actions:

Edit `AndroidManifest.xml`:

```diff
  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:windowSoftInputMode="adjustResize"
+   android:launchMode="singleTop"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
    <intent-filter>
64 65
      <action android:name="android.intent.action.MAIN" />
      <category android:name="android.intent.category.LAUNCHER" />
66 67 68 69 70 71
    </intent-filter>
+   <intent-filter>
+     <action android:name="fcm.ACTION.HELLO" />
+     <category android:name="android.intent.category.DEFAULT" />
+   </intent-filter>
  </activity>
72
```
73 74 75 76 77 78

Notes:
- `launchMode="singleTop"` is to reuse MainActivity
- replace `"fcm.ACTION.HELLO"` by the `click_action` you want to match


79
If you are using RN < 0.30.0 and react-native-fcm < 1.0.16, pass intent into package, edit `MainActivity.java`:
80

Libin Lu's avatar
Libin Lu committed
81
- RN 0.28:
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

```diff
  import com.facebook.react.ReactActivity;
+ import android.content.Intent;

  public class MainActivity extends ReactActivity {

+   @Override
+   public void onNewIntent (Intent intent) {
+     super.onNewIntent(intent);
+       setIntent(intent);
+   }       
```

- RN <= 0.27:

```diff
  import com.facebook.react.ReactActivity;
+ import android.content.Intent;

  public class MainActivity extends ReactActivity {

+   @Override
+   protected void onNewIntent (Intent intent) {
+     super.onNewIntent(intent);
+       setIntent(intent);
+   }       
109
```
Libin Lu's avatar
init  
Libin Lu committed
110

111 112 113
Notes:
- `@Override` is added to update intent on notification click

114
## IOS Configuration
Libin Lu's avatar
init  
Libin Lu committed
115

Libin Lu's avatar
Libin Lu committed
116 117
### Pod approach:

118 119 120
Make sure you have Cocoapods version > 1.0

Install the `Firebase/Messaging` pod:
Libin Lu's avatar
Libin Lu committed
121 122 123 124
```
cd ios && pod init
pod install Firebase/Messaging
```
Libin Lu's avatar
init  
Libin Lu committed
125

Libin Lu's avatar
Libin Lu committed
126
### Non Cocoapod approach
127 128 129

1. Download the Firebase SDK framework from [Integrate without CocoaPods](https://firebase.google.com/docs/ios/setup#frameworks)
2. Follow the `README` to link frameworks (Analytics+Messaging)
Libin Lu's avatar
Libin Lu committed
130 131

### Shared steps
Libin Lu's avatar
Libin Lu committed
132 133
Edit `AppDelegate.h`:
```diff
Libin Lu's avatar
Libin Lu committed
134 135
+ @import UserNotifications;
+
Libin Lu's avatar
Libin Lu committed
136 137 138
+ @interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>
- @interface AppDelegate : UIResponder <UIApplicationDelegate>
```
Libin Lu's avatar
init  
Libin Lu committed
139

140 141 142 143 144 145 146 147 148
Edit `AppDelegate.m`:
```diff
+ #import "RNFIRMessaging.h"
  //...

  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  {
  //...
+   [FIRApp configure];
Libin Lu's avatar
Libin Lu committed
149 150 151
+   #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
+   [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
+   #endif
152
  }
Libin Lu's avatar
init  
Libin Lu committed
153

Libin Lu's avatar
Libin Lu committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
+ #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
+ - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification + + withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
+ {
+   [[NSNotificationCenter defaultCenter] postNotificationName:FCMNotificationReceived object:self userInfo:notification.request.content.userInfo];
+   completionHandler(UNNotificationPresentationOptionAlert);
+ }

+ - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
+ {
+   [[NSNotificationCenter defaultCenter] postNotificationName:FCMNotificationReceived object:self userInfo:response.notification.request.content.userInfo];
+ }
+ #else
+ -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
+   [[NSNotificationCenter defaultCenter] postNotificationName:FCMNotificationReceived object:self + userInfo:notification.userInfo];
+ }
+ 
+ - (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
+   [[NSNotificationCenter defaultCenter] postNotificationName:FCMNotificationReceived object:self userInfo:userInfo];
+   completionHandler(UIBackgroundFetchResultNoData);
173
+ }
Libin Lu's avatar
Libin Lu committed
174
+ #endif
175
```
Libin Lu's avatar
init  
Libin Lu committed
176 177

### FCM config file
178

179
In [firebase console](https://console.firebase.google.com/), you can get `google-services.json` file and place it in `android/app` directory and get `GoogleService-Info.plist` file and place it in `/ios/your-project-name` directory (next to your `Info.plist`)
Libin Lu's avatar
Libin Lu committed
180
 
Libin Lu's avatar
Libin Lu committed
181
## Setup Local Notifications
Libin Lu's avatar
Libin Lu committed
182
NOTE: local notification does NOT have any dependency on FCM library but you still need to include Firebase to compile. If there are enough demand to use this functionality alone, I will separate it out into another repo
Libin Lu's avatar
Libin Lu committed
183

Libin Lu's avatar
Libin Lu committed
184
### IOS
Libin Lu's avatar
Libin Lu committed
185 186 187 188 189 190 191 192 193

Edit Appdelegate.m
```diff
+ -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification 
+ {
+   [[NSNotificationCenter defaultCenter] postNotificationName:FCMLocalNotificationReceived object:self userInfo:notification.userInfo];
+ }
```
 
Libin Lu's avatar
Libin Lu committed
194
### Android
Libin Lu's avatar
Libin Lu committed
195 196 197 198 199 200
Edit AndroidManifest.xml
```diff
  <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
+ <uses-permission android:name="android.permission.VIBRATE" />
 
Libin Lu's avatar
Libin Lu committed
201 202 203 204 205 206 207 208 209 210 211
  <application
+      <receiver android:name="com.evollu.react.fcm.FIRLocalMessagingPublisher"/>
+      <receiver android:enabled="true" android:exported="true"  android:name="com.evollu.react.fcm.FIRSystemBootEventReceiver">
+          <intent-filter>
+              <action android:name="android.intent.action.BOOT_COMPLETED"/>
+              <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
+              <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
+              <category android:name="android.intent.category.DEFAULT" />
+          </intent-filter>
+      </receiver>
  </application>
Libin Lu's avatar
Libin Lu committed
212 213 214
``` 
NOTE: `com.evollu.react.fcm.FIRLocalMessagingPublisher` is required for presenting local notifications. `com.evollu.react.fcm.FIRSystemBootEventReceiver` is required only if you need to schedule future or recurring local notifications

Libin Lu's avatar
init  
Libin Lu committed
215

Libin Lu's avatar
Libin Lu committed
216
## Usage
Libin Lu's avatar
init  
Libin Lu committed
217 218

```javascript
219
import FCM from 'react-native-fcm';
Goran Gajic's avatar
Goran Gajic committed
220

221
class App extends Component {
Libin Lu's avatar
Libin Lu committed
222 223 224 225 226 227 228 229
    componentDidMount() {
        FCM.requestPermissions(); // for iOS
        FCM.getFCMToken().then(token => {
            console.log(token)
            // store fcm token in your server
        });
        this.notificationUnsubscribe = FCM.on('notification', (notif) => {
            // there are two parts of notif. notif.notification contains the notification payload, notif.data contains data payload
Libin Lu's avatar
Libin Lu committed
230 231 232 233 234 235
            if(notif.local_notification){
              //this is a local notification
            }
            if(notif.opened_from_tray){
              //app is open/resumed because user clicked banner
            }
Libin Lu's avatar
Libin Lu committed
236 237 238 239 240 241
        });
        this.refreshUnsubscribe = FCM.on('refreshToken', (token) => {
            console.log(token)
            // fcm token may not be available on first load, catch it here
        });
    }
Goran Gajic's avatar
Goran Gajic committed
242

Libin Lu's avatar
Libin Lu committed
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    componentWillUnmount() {
        // prevent leaking
        this.refreshUnsubscribe();
        this.notificationUnsubscribe();
    }
 
    otherMethods(){
        FCM.subscribeToTopic('/topics/foo-bar');
        FCM.unsubscribeFromTopic('/topics/foo-bar');
        FCM.getInitialNotification().then(...);
        FCM.presentLocalNotification({
            id: "UNIQ_ID_STRING",                               // (optional for instant notification)
            title: "My Notification Title",                     // as FCM payload
            body: "My Notification Message",                    // as FCM payload (required)
            sound: "default",                                   // as FCM payload
            priority: "high",                                   // as FCM payload
Libin Lu's avatar
Libin Lu committed
259 260 261
            click_action: "ACTION",                             // as FCM payload
            badge: 10,                                          // as FCM payload IOS only, set 0 to clear badges
            number: 10,                                         // Android only
Libin Lu's avatar
Libin Lu committed
262 263
            ticker: "My Notification Ticker",                   // Android only
            auto_cancel: true,                                  // Android only (default true)
Libin Lu's avatar
Libin Lu committed
264
            large_icon: "ic_launcher",                           // Android only
Libin Lu's avatar
Libin Lu committed
265 266 267 268
            icon: "ic_notification",                            // as FCM payload
            big_text: "Show when notification is expanded",     // Android only
            sub_text: "This is a subText",                      // Android only
            color: "red",                                       // Android only
Libin Lu's avatar
Libin Lu committed
269
            vibrate: 300,                                       // Android only default: 300, no vibration if you pass null
Libin Lu's avatar
Libin Lu committed
270 271 272 273 274 275
            tag: 'some_tag',                                    // Android only
            group: "group",                                     // Android only
            my_custom_data:'my_custom_field_value',             // extra data you want to throw
        });
 
        FCM.scheduleLocalNotification({
Libin Lu's avatar
Libin Lu committed
276
            fire_date: new Date().getTime(),      //react convert is used, accept epoch time or ISO string
Libin Lu's avatar
Libin Lu committed
277
            id: "UNIQ_ID_STRING",    //REQUIRED! this is what you use to lookup and delete notification. In android notification with same ID will override each other
Libin Lu's avatar
Libin Lu committed
278 279
            body: "from future past",
            repeat_interval: "week" //day, hour
Libin Lu's avatar
Libin Lu committed
280 281 282 283 284 285
        })
 
        FCM.getScheduledLocalNotifications().then(...);
        FCM.cancelLocalNotification("UNIQ_ID_STRING");
        FCM.cancelAllLocalNotifications();
        FCM.setBadgeNumber();
Libin Lu's avatar
Libin Lu committed
286
        FCM.getBadgeNumber().then(...);
Libin Lu's avatar
Libin Lu committed
287
    }
288
}
Libin Lu's avatar
init  
Libin Lu committed
289 290
```

291
### Behaviour when sending `notification` and `data` payload through GCM
292
- When app is not running and user clicks notification, notification data will be passed into `FCM.initialData`
Libin Lu's avatar
Libin Lu committed
293

Libin Lu's avatar
Libin Lu committed
294 295 296 297 298
- When app is running in background (the tricky one, I strongly suggest you try it out yourself)
 - IOS will receive notificaton from `FCMNotificationReceived` event
    * if you pass `content_available` flag true, you will receive one when app is in background and another one when user resume the app. [more info](http://www.rahuljiresal.com/2015/03/retract-push-notifications-on-ios/)
    * if you just pass `notification`, you will only receive one when user resume the app.
    * you will not see banner if `notification->body` is not defined.
299 300 301 302 303 304 305
 - Android will receive notificaton from `FCMNotificationReceived` event
    * if you pass `notification` payload. it will receive data when user click on notification
    * if you pass `data` payload only, it will receive data when in background

   e.g. fcm payload looks like:

   ```json
Libin Lu's avatar
Libin Lu committed
306 307 308 309 310 311 312 313 314 315 316 317 318
   {
      "to":"some_device_token",
      "content_available": true,
      "notification": {
          "title": "hello",
          "body": "yo",
          "click_action": "fcm.ACTION.HELLO"
      },
      "data": {
          "extra":"juice"
      }
    }
    ```
319 320 321 322 323 324 325

    and event callback will receive as:
    
    - Android
      ```json
      {
        "fcm": {"action": "fcm.ACTION.HELLO"},
Libin Lu's avatar
Libin Lu committed
326
        "opened_from_tray": 1,
327 328 329 330 331 332 333 334
        "extra": "juice"
      }
      ```
    
    - iOS
      ```json
      {
        "apns": {"action_category": "fcm.ACTION.HELLO"},
Libin Lu's avatar
Libin Lu committed
335
        "opened_from_tray": 1,
336 337 338
        "extra": "juice"
      }
      ```
339

Libin Lu's avatar
Libin Lu committed
340
- When app is running in foreground
341
 - IOS will receive notification and android **won't** (better not to do anything in foreground for hybrid and send a seprate data message.)
342

343
NOTE: it is recommend not to rely on `data` payload for click_action as it can be overwritten (check [this](http://stackoverflow.com/questions/33738848/handle-multiple-notifications-with-gcm)).
344

Libin Lu's avatar
init  
Libin Lu committed
345
## Q & A
346

Libin Lu's avatar
Libin Lu committed
347 348 349 350 351 352
#### Why do you build another local notification
Yes there are `react-native-push-notification` and `react-native-system-notification` which are great libraries. However
- We want a unified local notification library but people are reporting using react-native-push-notification with this repo has compatibility issue as `react-native-push-notification` also sets up GCM.
- We want to have local notification to have similar syntax as remote notification payload.
- The PushNotificationIOS by react native team is still missing features that recurring, so we are adding it here

353
#### My Android build is failing
Libin Lu's avatar
Libin Lu committed
354
Try update your SDK and google play service
355

356
#### I can't get notification when app is killed
357 358
If you send notification with `data` only, you can only get the data message when app is in foreground or background. Killed app doesn't trigger `FCMNotificationReceived`. Use `notification` in the payload instead.

Libin Lu's avatar
Libin Lu committed
359
#### App running in background doesn't trigger `FCMNotificationReceived` when receiving hybrid notification [Android]
360
These is [an issue opened for that](https://github.com/google/gcm/issues/63). Behavior is not consistent between 2 platforms
361

Libin Lu's avatar
Libin Lu committed
362
#### Android notification is showing a white icon
363 364
Since Lollipop, the push notification icon is required to be all white, otherwise it will be a white circle.

Libin Lu's avatar
Libin Lu committed
365 366 367
#### iOS not receiving notification when the app running in the background
- Try adding Background Modes permission in Xcode->Click on project file->Capabilities tab->Background Modes->Remote Notifications

368 369 370 371 372 373 374
#### I am using Proguard
You need to add this to your `android/app/proguard-rules.pro`:
```
# Google Play Services
-keep class com.google.android.gms.** { *; }
-dontwarn com.google.android.gms.**
```
Libin Lu's avatar
init  
Libin Lu committed
375

Libin Lu's avatar
Libin Lu committed
376
#### How do I tell if user clicks the notification banner?
Libin Lu's avatar
Libin Lu committed
377
Check open from tray flag in notification. It will be either 0 or 1 for iOS and undefined or 1 for android. I decide for iOS base on [this](http://stackoverflow.com/questions/20569201/remote-notification-method-called-twice), and for android I set it if notification is triggered by intent change.
Libin Lu's avatar
Libin Lu committed
378

Libin Lu's avatar
Libin Lu committed
379
#### Android notification doesn't vibrate/show head-up display etc
Libin Lu's avatar
Libin Lu committed
380 381
All available features are [here](https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support). FCM may add more support in the future but there is no timeline. If you need these features now, send notification with `data` only and creating notification locally is the only way.
Or you can send `data` using FCM and build a local notification
Libin Lu's avatar
Libin Lu committed
382

Libin Lu's avatar
Libin Lu committed
383 384 385
#### How do I do xxx with FCM?
check out [official docs and see if they support](https://firebase.google.com/docs/cloud-messaging/concept-options)

Libin Lu's avatar
Libin Lu committed
386
#### I want to add advanced feature that FCM doesn't support for remote notification
Libin Lu's avatar
Libin Lu committed
387
You can either wait for FCM to develop it or you have to write native code to create notifications.
Libin Lu's avatar
Libin Lu committed
388 389
- for iOS, you can do it in `didReceiveRemoteNotification` in `appDelegate.m`
- for android, you can do it by implementing a service similar to "com.evollu.react.fcm.MessagingService"
Libin Lu's avatar
Libin Lu committed
390

Libin Lu's avatar
Libin Lu committed
391 392
Or if you have a good way to wake up react native javascript thread please let me know, although I'm worring waking up the whole application is too expensive.

Libin Lu's avatar
Libin Lu committed
393 394 395 396 397 398 399 400 401 402 403 404
#### What about new notifications in iOS 10
Congratulations, now you have 5 notification handler to register!
in sum
- `willPresentNotification` is introduced in iOS 10 and will only be called when local/remote notification will show up. This allows you to run some code **before** notification shows up. You can also decide how to show the notification.
- `didReceiveNotificationResponse` is introduced in iOS 10 and provides user's response together with local/remote notification. It could be swipe, text input etc.
- `didReceiveLocalNotification` is for iOS 9 and below. Triggered when user clicks local notification. replaced by `didReceiveNotificationResponse`
- `didReceiveRemoteNotification` is for iOS 9 and below. Triggered when remote notification received.
- `didReceiveRemoteNotification:fetchCompletionHandler` is for both iOS 9 and 10. it gets triggered 2 times for each remote notification. 1st time when notification is received. 2nd time when notification is clicked. in iOS 9, it serves us the purpose of both `willPresentNotification` and `didReceiveNotificationResponse` but for remote notification only. in iOS 10, you don't need it in most of the case unless you need to do background fetching

Great, how do I configure for FCM?
It is up to you! FCM is just a bridging library that passes notification into javascript world. You can define your own NSDictionary and pass it into notification.

405 406
#### Some features are missing
Issues and pull requests are welcome. Let's make this thing better!
Libin Lu's avatar
Libin Lu committed
407 408
 
#### Thanks
Libin Lu's avatar
Libin Lu committed
409
Local notification implementation is inspired by react-native-push-notification by zo0r