diff --git a/.travis.yml b/.travis.yml index 4909f83ca..0fe294a6f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,3 @@ language: node_js node_js: - - "6" + - "7" diff --git a/README.md b/README.md index 406166feb..01754518b 100644 --- a/README.md +++ b/README.md @@ -4,23 +4,21 @@ Handle all the aspects of push notifications for your app, including remote and **All the native iOS notifications features are supported!** +_For information regarding proper integration with [react-native-navigation](https://github.com/wix/react-native-navigation), follow [this wiki](https://github.com/wix/react-native-notifications/wiki/Android:-working-with-RNN)._ + -## Supported Features ### iOS -- [Remote notifications](#handling-received-notifications). -- [Local notifications](#triggering-local-notifications). -- [Background notifications](#managed-notifications-ios-only). -- [Managed notifications](#managed-notifications-ios-only) (notifications that can be cleared from the server, like Facebook messenger and Whatsapp web). -- [PushKit API](#pushkit-api-ios-only) for VoIP and other background messages. -- [Interactive notifications](#interactive--actionable-notifications-ios-only) that allows you to provide additional functionality to your users outside of your application. +Interactive notifications example -![Interactive notifications example](https://s3.amazonaws.com/nrjio/interactive.gif) +- Remote (push) notifications +- Local notifications +- Background/Managed notifications (notifications that can be cleared from the server, like Facebook messenger and Whatsapp web) +- PushKit API (for VoIP and other background messages) +- Interactive notifications (allows you to provide additional functionality to your users outside of your application such as action buttons) ### Android ->**Please advise that Android support is a work in progress and is subject to breaking changes in the near future** - - Receiving notifications in any App state (foreground, background, "dead") - Built-in notification drawer management - High degree of code extensibility to allow for advanced custom layouts and any specific notifications behavior as available by [Android's API](https://developer.android.com/training/notify-user/build-notification.html) @@ -28,593 +26,16 @@ Handle all the aspects of push notifications for your app, including remote and _Upcoming: local notifications, background-state Rx queue (iOS equivalent)_ -## Installation - -``` -$ npm install react-native-notifications --save -``` - -### iOS - -First, [Manully link](https://facebook.github.io/react-native/docs/linking-libraries-ios.html#manual-linking) the library to your Xcode project. - -Then, to enable notifications support add the following line at the top of your `AppDelegate.m` - -```objective-c -#import "RNNotifications.h" -``` - -And the following methods to support registration and receiving notifications: - -```objective-c -// Required to register for notifications -- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings -{ - [RNNotifications didRegisterUserNotificationSettings:notificationSettings]; -} - -- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken -{ - [RNNotifications didRegisterForRemoteNotificationsWithDeviceToken:deviceToken]; -} - -// Required for the notification event. -- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification { - [RNNotifications didReceiveRemoteNotification:notification]; -} - -// Required for the localNotification event. -- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification -{ - [RNNotifications didReceiveLocalNotification:notification]; -} -``` - -### Android - - -Add a reference to the library's native code in your global `settings.gradle`: - -```gradle -include ':reactnativenotifications' -project(':reactnativenotifications').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-notifications/android') -``` - -Declare the library as a dependency in your **app-project's** `build.gradle`: - -```gradle -dependencies { - // ... - - compile project(':reactnativenotifications') -} -``` - -Add the library to your `MainApplication.java`: - -```java -import com.wix.reactnativenotifications.RNNotificationsPackage; - -... - - @Override - protected List getPackages() { - return Arrays.asList( - new MainReactPackage(), - ... - new RNNotificationsPackage(MainApplication.this), -``` - -### Receiving push notifications - -> This section is only necessary in case you wish to **receive** push notifications in your React-Native app. - -Push notifications on Android are managed and dispatched using [Google's GCM service](https://developers.google.com/cloud-messaging/gcm) (now integrated into Firebase). The following installation steps are a TL;DR of [Google's GCM setup guide](https://developers.google.com/cloud-messaging/android/client). You can follow them to get GCM integrated quickly, but we recommend that you will in the very least have a peek at the guide's overview. - -#### Step #1: Subscribe to Google's GCM - -To set GCM in your app, you must first create a Google API-project and obtain a **Sender ID** and a **Server API Key**. If you have no existing API project yet, the easiest way to go about in creating one is using [this step-by-step installation process](https://developers.google.com/mobile/add); Use [this tutorial](https://code.tutsplus.com/tutorials/how-to-get-started-with-push-notifications-on-android--cms-25870) for insturctions. - -Alternatively, follow [Google's complete guide](https://developers.google.com/cloud-messaging/android/client#create-an-api-project). - -#### Step #2: Add Sender ID to Manifest File - -Once obtained, bundle the Sender ID onto your main `manifest.xml` file: - -```gradle - -... - - ... - // Replace '1234567890' with your sender ID. - // IMPORTANT: Leave the trailing \0 intact!!! - - - - -``` - - ---- - -## Register to Push Notifications - -### iOS - -In order to handle notifications, you must register before- handle `remoteNotificationsRegistered` event. - -In your React Native app: - -```javascript -import NotificationsIOS from 'react-native-notifications'; - -class App extends Component { - constructor() { - NotificationsIOS.addEventListener('remoteNotificationsRegistered', this.onPushRegistered.bind(this)); - NotificationsIOS.requestPermissions(); - } - - onPushRegistered(deviceToken) { - console.log("Device Token Received", deviceToken); - } - - componentWillUnmount() { - // prevent memory leaks! - NotificationsIOS.removeEventListener('remoteNotificationsRegistered', this.onPushRegistered.bind(this)); - } -} - -``` - -When you have the device token, POST it to your server and register the device in your notifications provider (Amazon SNS, Azure, etc.). - -### Android - -The React-Native code equivalent on Android is: - -```javascript -import {NotificationsAndroid} from 'react-native-notifications'; - -// On Android, we allow for only one (global) listener per each event type. -NotificationsAndroid.setRegistrationTokenUpdateListener((deviceToken) => { - console.log('Push-notifications regsitered!', deviceToken) -}); - -``` - -`deviceToken` being the token used to identify the device on the GCM. - ---- - - -## Handling Received Notifications - -### iOS - -When you receive a notification, the application can be in one of the following states: - -1. **Forground**- When the app in running and is used by the user right now. in this case, `notificationReceivedForeground` event will be fired. -2. **Background**- When the app is running but in background state. in this case, `notificationReceivedBackground` event will be fired. -3. **Notification Opened**- When you open the notifications from the notification center. in this case, `notificationOpened` event will be fired. - -Example: - -```javascript -constructor() { - NotificationsIOS.addEventListener('notificationReceivedForeground', this.onNotificationReceivedForeground.bind(this)); - NotificationsIOS.addEventListener('notificationReceivedBackground', this.onNotificationReceivedBackground.bind(this)); - NotificationsIOS.addEventListener('notificationOpened', this.onNotificationOpened.bind(this)); -} - -onNotificationReceivedForeground(notification) { - console.log("Notification Received - Foreground", notification); -} - -onNotificationReceivedBackground(notification) { - console.log("Notification Received - Background", notification); -} - -onNotificationOpened(notification) { - console.log("Notification opened by device user", notification); -} - -componentWillUnmount() { - // Don't forget to remove the event listeners to prevent memory leaks! - NotificationsIOS.removeEventListener('notificationReceivedForeground', this.onNotificationReceivedForeground.bind(this)); - NotificationsIOS.removeEventListener('notificationReceivedBackground', this.onNotificationReceivedBackground.bind(this)); - NotificationsIOS.removeEventListener('notificationOpened', this.onNotificationOpened.bind(this)); -} -``` - -#### Notification Object -When you receive a push notification, you'll get an instance of `IOSNotification` object, contains the following methods: - -- **`getMessage()`**- returns the notification's main message string. -- **`getSound()`**- returns the sound string from the `aps` object. -- **`getBadgeCount()`**- returns the badge count number from the `aps` object. -- **`getCategory()`**- returns the category from the `aps` object (related to interactive notifications). -- **`getData()`**- returns the data payload (additional info) of the notification. -- **`getType()`**- returns `managed` for managed notifications, otherwise returns `regular`. - -#### Background Queue (Important!) -When a push notification is opened but the app is not running, the application will be in a **cold launch** state, until the JS engine is up and ready to handle the notification. -The application will collect the events (notifications, actions, etc.) that happend during the cold launch for you. - -When your app is ready (most of the time it's after the call to `requestPermissions()`), just call to `NotificationsIOS.consumeBackgroundQueue();` in order to consume the background queue. For more info see `index.ios.js` in the example app. - -### Android - -```javascript -import {NotificationsAndroid} from 'react-native-notifications'; - -// On Android, we allow for only one (global) listener per each event type. -NotificationsAndroid.setNotificationReceivedListener((notification) => { - console.log("Notification received on device", notification.getData()); -}); -NotificationsAndroid.setNotificationOpenedListener((notification) => { - console.log("Notification opened by device user", notification.getData()); -}); -``` - -#### Notification Object -- **`getData()`**- content of the `data` section of the original message (sent to GCM). -- **`getTitle()`**- Convenience for returning `data.title`. -- **`getMessage()`**- Convenience for returning `data.body`. - ---- - -## Querying initial notification - -React-Native's [`PushNotificationsIOS.getInitialNotification()`](https://facebook.github.io/react-native/docs/pushnotificationios.html#getinitialnotification) allows for the async retrieval of the original notification used to open the App on iOS, but it has no equivalent implementation for Android. - -We provide a similar implementation on Android using `PendingNotifications.getInitialNotification()` which returns a promise: - -```javascript -import {NotificationsAndroid, PendingNotifications} from 'react-native-notifications'; - -PendingNotifications.getInitialNotification() - .then((notification) => { - console.log("Initial notification was:", (notification ? notification.getData() : 'N/A'); - }) - .catch((err) => console.error("getInitialNotifiation() failed", err)); - -``` - -> Notifications are considered 'initial' under the following terms: - -> - User tapped on a notification, _AND_ - -> - App was either not running at all ("dead" state), _OR_ it existed in the background with **no running activities** associated with it. - - -## Triggering Local Notifications - -### iOS - -You can manually trigger local notifications in your JS code, to be posted immediately or in the future. -Triggering local notifications is fully compatible with React Native `PushNotificationsIOS` library. - -Example: - -```javascript -let localNotification = NotificationsIOS.localNotification({ - alertBody: "Local notificiation!", - alertTitle: "Local Notification Title", - alertAction: "Click here to open", - soundName: "chime.aiff", - category: "SOME_CATEGORY", - userInfo: { } -}); -``` - -Notification object contains: - -- **`fireDate`**- The date and time when the system should deliver the notification (optinal - default is immidiate dispatch). -- `alertBody`- The message displayed in the notification alert. -- `alertTitle`- The title of the notification, displayed in the notifications center. -- `alertAction`- The "action" displayed beneath an actionable notification. -- `soundName`- The sound played when the notification is fired (optional). -- `category`- The category of this notification, required for [interactive notifications](#interactive--actionable-notifications-ios-only) (optional). -- `userInfo`- An optional object containing additional notification data. - -### Android - -Much like on iOS, notifications can be triggered locally. The API to do so is a simplified version of the iOS equivalent that works more natually with the Android perception of push (remote) notifications: - -```javascript -NotificationsAndroid.localNotification({ - title: "Local notification", - body: "This notification was generated by the app!", - extra: "data" -}); -``` - -Upon notification opening (tapping by the device user), all data fields will be delivered as-is). - -### Cancel Local Notification -The `NotificationsIOS.localNotification()` and `NotificationsAndroid.localNotification()` methods return unique `notificationId` values, which can be used in order to cancel specific local notifications. You can cancel local notification by calling `NotificationsIOS.cancelLocalNotification(notificationId)` or `NotificationsAndroid.cancelLocalNotification(notificationId)`. - -Example (iOS): - -```javascript -let someLocalNotification = NotificationsIOS.localNotification({ - alertBody: "Local notificiation!", - alertTitle: "Local Notification Title", - alertAction: "Click here to open", - soundName: "chime.aiff", - category: "SOME_CATEGORY", - userInfo: { } -}); - -NotificationsIOS.cancelLocalNotification(someLocalNotification); -``` - -### Cancel All Local Notifications (iOS-only!) - -```javascript -NotificationsIOS.cancelAllLocalNotifications(); -``` - ---- - -## Badge Counts - -Setting a badge is possible on iOS and Android. In addition to this retreiving the badge is possible on iOS but _not_ yet supported on Android. - -To add `getBadgeCount` support on Android or to read up on what particular devices are supported [check here](https://github.com/leolin310148/ShortcutBadger). - -### iOS -```js -NotificationsIOS.setBadgeCount(10); -NotificationsIOS.getBadgeCount(function(count) { - console.log('Badge count is', count); // 10 -}); -``` - -### Android -```js -NotificationsAndroid.setBadgeCount(10); -``` - - -## Managed Notifications (iOS only) - -Managed notifications are notifications that can be cleared by a server request. -You can find this feature in facebook messenger, when you receive a message in your mobile, but open it in facebook web. More examples are Whatsapp web and gmail app. - -In order to handle managed notifications, your app must support background notifications, and the server should send the notifications you'd like to "manage" a bit differently. Let's start. - -First, enable the *Remote notifications* checkbox under **capabilities - Background Modes**: -![Background Modes](http://docs.urbanairship.com/_images/ios-background-push-capabilities1.png) - -Then, add the following lines to `info.plist`: - -```xml -UIBackgroundModes - - remote-notification - -``` - -That's it for the client side! - -Now the server should push the notification a bit differently- background instead of reguler. You should also provide the action (`CREATE` notification or `CLEAR` notification), and `notificationId` as a unique identifier of the notification. - -**Regular** notification payload: - -```javascript -{ - aps: { - alert: { - body: "This is regular notification" - }, - badge: 5, - sound: "chime.aiff", - } -} -``` - -**Managed** notification payload: - -```javascript -{ - aps: { - "content-available": 1 - }, - managedAps: { - action: "CREATE", // set it to "CLEAR" in order to clear the notification remotely - notificationId: "1234", // must be unique identifier - sound: "chime.aiff", - alert: { - body: "This is managed notification" - } - } -} -``` - ---- - -## PushKit API (iOS only) - -The PushKit framework provides the classes for your iOS apps to receive background pushes from remote servers. it has better support for background notifications compared to regular push notifications with `content-available: 1`. More info in [iOS PushKit documentation](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/PushKit_Framework/). - -### Register to PushKit -After [preparing your app to receive VoIP push notifications](https://developer.apple.com/library/ios/documentation/Performance/Conceptual/EnergyGuide-iOS/OptimizeVoIP.html), add the following lines to `appDelegate.m` in order to support PushKit events: - -```objective-c -#import "RNNotifications.h" -#import -``` - -And the following methods: - -```objective-c -// PushKit API Support -- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type -{ - [RNNotifications didUpdatePushCredentials:credentials forType:type]; -} - -- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type -{ - [RNNotifications didReceiveRemoteNotification:payload.dictionaryPayload]; -} -``` - -In your ReactNative code, add event handler for `pushKitRegistered` event and call to `registerPushKit()`: - -```javascript -constructor() { - NotificationsIOS.addEventListener('pushKitRegistered', this.onPushKitRegistered.bind(this)); - NotificationsIOS.registerPushKit(); -} - -onPushKitRegistered(deviceToken) { - console.log("PushKit Token Received: " + deviceToken); -} - -componentWillUnmount() { - // Don't forget to remove the event listeners to prevent memory leaks! - NotificationsIOS.removeEventListener('pushKitRegistered', onPushKitRegistered(this)); -} -``` - -> 1. Notice that PushKit device token and regular notifications device token are different, so you must handle two different tokens in the server side in order to support this feature. -> 2. PushKit will not request permissions from the user for push notifications. - - ---- - -## Interactive / Actionable Notifications - -> This section provides description for iOS. For notifications customization on Android, refer to [our wiki](https://github.com/wix/react-native-notifications/wiki/Android-Customizations#customizing-notifications-layout). - -Interactive notifications allow you to reply to a message right from the notification banner or take action right from the lock screen. - -On the Lock screen and within Notification Center, you swipe from right to left -to reveal actions. Destructive actions, like trashing an email, are color-coded red. Relatively neutral actions, like dismissing an alert or declining an invitation, are color-coded gray. - -For banners, you pull down to reveal actions as buttons. For popups, the actions are immediately visible — the buttons are right there. - -You can find more info about interactive notifications [here](http://www.imore.com/interactive-notifications-ios-8-explained). - -![Interactive Notifications](http://i.imgur.com/XrVzy9w.gif) - - -Notification **actions** allow the user to interact with a given notification. - -Notification **categories** allow you to group multiple actions together, and to connect the actions with the push notification itself. - -In order to support interactive notifications, firstly add the following methods to `appDelegate.m` file: - -```objective-c -// Required for the notification actions. -- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler -{ - [RNNotifications handleActionWithIdentifier:identifier forLocalNotification:notification withResponseInfo:responseInfo completionHandler:completionHandler]; -} - -- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler -{ - [RNNotifications handleActionWithIdentifier:identifier forRemoteNotification:userInfo withResponseInfo:responseInfo completionHandler:completionHandler]; -} -``` - -Then, follow the basic workflow of adding interactive notifications to your app: - -1. Config the actions. -2. Group actions together into categories. -3. Register to push notifications with the configured categories. -4. Push a notification (or trigger a [local](#triggering-local-notifications) one) with the configured category name. - -### Example -#### Config the Actions -We will config two actions: upvote and reply. - -```javascript -import NotificationsIOS, { NotificationAction, NotificationCategory } from 'react-native-notifications'; - -let upvoteAction = new NotificationAction({ - activationMode: "background", - title: String.fromCodePoint(0x1F44D), - identifier: "UPVOTE_ACTION" -}, (action, completed) => { - console.log("ACTION RECEIVED"); - console.log(JSON.stringify(action)); - - // You must call to completed(), otherwise the action will not be triggered - completed(); -}); - -let replyAction = new NotificationAction({ - activationMode: "background", - title: "Reply", - behavior: "textInput", - authenticationRequired: true, - identifier: "REPLY_ACTION" -}, (action, completed) => { - console.log("ACTION RECEIVED"); - console.log(action); - - completed(); -}); - -``` - -#### Config the Category -We will group `upvote` action and `reply` action into a single category: `EXAMPLE_CATEGORY `. If the notification contains `EXAMPLE_CATEGORY ` under `category` field, those actions will appear. - -```javascript -let exampleCategory = new NotificationCategory({ - identifier: "EXAMPLE_CATEGORY", - actions: [upvoteAction, replyAction], - context: "default" -}); -``` - -#### Register to Push Notifications -Instead of basic registration like we've done before, we will register the device to push notifications with the category we've just created. - -```javascript -NotificationsIOS.requestPermissions([exampleCategory]); -``` - -#### Push an Interactive Notification -Notification payload should look like this: - -```javascript -{ - aps: { - // ... (alert, sound, badge, etc) - category: "EXAMPLE_CATEGORY" - } -} -``` - -The [example app](https://github.com/wix/react-native-notifications/tree/master/example) contains this interactive notification example, you can follow there. - -### `NotificationAction` Payload - -- `title` - Action button title. -- `identifier` - Action identifier (must be unique). -- `activationMode` - Indicating whether the app should activate to the foreground or background. - - `foreground` (default) - Activate the app and put it in the foreground. - - `background` - Activate the app and put it in the background. If the app is already in the foreground, it remains in the foreground. -- `behavior` - Indicating additional behavior that the action supports. - - `default` - No additional behavior. - - `textInput` - When button is tapped, the action opens a text input. the text will be delivered to your action callback. -- `destructive` - A Boolean value indicating whether the action is destructive. When the value of this property is `true`, the system displays the corresponding button differently to indicate that the action is destructive. -- `authenticationRequired` - A Boolean value indicating whether the user must unlock the device before the action is performed. - -### `NotificationCategory` Payload +# Table of Content -- `identifier` - The name of the action group (must be unique). -- `actions` - An array of `NotificationAction` objects, which related to this category. -- `context` - Indicating the amount of space available for displaying actions in a notification. - - `default` (default) - Displayes up to 4 actions (full UI). - - `minimal` - Displays up tp 2 actions (minimal UI). +- [Installation and setup](./docs/installation.md) - Setting up the library in your app +- [Subscription](./docs/subscription.md) - Signing in to push notifications vendors (e.g. GCM) +- [Notification Events (notfications core)](./docs/notificationsEvents.md) - Handling push notification arrival, notification opening by users +- [Local notifications](./docs/localNotifications.md) - Manually triggering notifications (i.e. not via push) +- [Advanced iOS topics](./docs/advancedIos.md) - e.g. managed notifications, PushKit API, Notifications actions +- [Notifications layout control - Android (wiki page)](https://github.com/wix/react-native-notifications/wiki/Android:-Layout-Customization) - Learn how to fully customize your notifications layout on Android! - -## License +# License The MIT License. See [LICENSE](LICENSE) diff --git a/RNNotifications/RNNotifications.h b/RNNotifications/RNNotifications.h index 10a2c46a2..0936c00bf 100644 --- a/RNNotifications/RNNotifications.h +++ b/RNNotifications/RNNotifications.h @@ -8,11 +8,28 @@ #import #endif +#if __has_include() +#import +#elif __has_include("React/RCTConvert.h") +#import "React/RCTConvert.h" +#else +#import "RCTConvert.h" +#endif + +@interface RCTConvert (UILocalNotification) ++ (UILocalNotification *)UILocalNotification:(id)json; +@end + +@interface RCTConvert (UIBackgroundFetchResult) ++(UIBackgroundFetchResult *)UIBackgroundFetchResult:(id)json; +@end + @interface RNNotifications : NSObject typedef void (^RCTRemoteNotificationCallback)(UIBackgroundFetchResult result); + (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken; ++ (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error; + (void)didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings; + (void)didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type; diff --git a/RNNotifications/RNNotifications.m b/RNNotifications/RNNotifications.m index 09880045f..864e92fd4 100644 --- a/RNNotifications/RNNotifications.m +++ b/RNNotifications/RNNotifications.m @@ -2,9 +2,12 @@ #import #import #import "RNNotifications.h" -#import "RCTConvert.h" -#import "RCTUtils.h" +#import +#import #import "RNNotificationsBridgeQueue.h" +#import + +#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) #if __has_include("RCTBridge.h") #import "RCTBridge.h" @@ -22,6 +25,7 @@ NSString* const RNNotificationClearAction = @"CLEAR"; NSString* const RNNotificationsRegistered = @"RNNotificationsRegistered"; +NSString* const RNNotificationsRegistrationFailed = @"RNNotificationsRegistrationFailed"; NSString* const RNPushKitRegistered = @"RNPushKitRegistered"; NSString* const RNNotificationReceivedForeground = @"RNNotificationReceivedForeground"; NSString* const RNNotificationReceivedBackground = @"RNNotificationReceivedBackground"; @@ -53,17 +57,6 @@ @implementation RCTConvert (UIUserNotificationActionBehavior) }), UIUserNotificationActionBehaviorDefault, integerValue) @end -@implementation RCTConvert (UIBackgroundFetchResult) - -RCT_ENUM_CONVERTER(UIBackgroundFetchResult, (@{ - @"UIBackgroundFetchResultNewData": @(UIBackgroundFetchResultNewData), - @"UIBackgroundFetchResultNoData": @(UIBackgroundFetchResultNoData), - @"UIBackgroundFetchResultFailed": @(UIBackgroundFetchResultFailed), - }), UIBackgroundFetchResultNoData, integerValue) - -@end - - @implementation RCTConvert (UIMutableUserNotificationAction) + (UIMutableUserNotificationAction *)UIMutableUserNotificationAction:(id)json { @@ -101,27 +94,64 @@ + (UIMutableUserNotificationCategory *)UIMutableUserNotificationCategory:(id)jso } @end -@implementation RCTConvert (UILocalNotification) -+ (UILocalNotification *)UILocalNotification:(id)json +@implementation RCTConvert (UNNotificationRequest) ++ (UNNotificationRequest *)UNNotificationRequest:(id)json withId:(NSString*)notificationId { NSDictionary *details = [self NSDictionary:json]; - UILocalNotification* notification = [UILocalNotification new]; - notification.fireDate = [RCTConvert NSDate:details[@"fireDate"]]; - notification.alertBody = [RCTConvert NSString:details[@"alertBody"]]; - // alertTitle is a property on iOS 8.2 and above: - if ([notification respondsToSelector:@selector(setAlertTitle:)]) { - notification.alertTitle = [RCTConvert NSString:details[@"alertTitle"]]; + UNMutableNotificationContent *content = [UNMutableNotificationContent new]; + content.body = [RCTConvert NSString:details[@"alertBody"]]; + content.title = [RCTConvert NSString:details[@"alertTitle"]]; + content.sound = [RCTConvert NSString:details[@"soundName"]] + ? [UNNotificationSound soundNamed:[RCTConvert NSString:details[@"soundName"]]] + : [UNNotificationSound defaultSound]; + if ([RCTConvert BOOL:details[@"silent"]]) { + content.sound = nil; + } + content.userInfo = [RCTConvert NSDictionary:details[@"userInfo"]] ?: @{}; + content.categoryIdentifier = [RCTConvert NSString:details[@"category"]]; + + NSDate *triggerDate = [RCTConvert NSDate:details[@"fireDate"]]; + UNCalendarNotificationTrigger *trigger = nil; + if (triggerDate != nil) { + NSDateComponents *triggerDateComponents = [[NSCalendar currentCalendar] + components:NSCalendarUnitYear + + NSCalendarUnitMonth + NSCalendarUnitDay + + NSCalendarUnitHour + NSCalendarUnitMinute + + NSCalendarUnitSecond + NSCalendarUnitTimeZone + fromDate:triggerDate]; + trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDateComponents + repeats:NO]; } - notification.alertAction = [RCTConvert NSString:details[@"alertAction"]]; - notification.soundName = [RCTConvert NSString:details[@"soundName"]] ?: UILocalNotificationDefaultSoundName; - notification.userInfo = [RCTConvert NSDictionary:details[@"userInfo"]] ?: @{}; - notification.category = [RCTConvert NSString:details[@"category"]]; - return notification; + return [UNNotificationRequest requestWithIdentifier:notificationId + content:content trigger:trigger]; } @end +static NSDictionary *RCTFormatUNNotification(UNNotification *notification) +{ + NSMutableDictionary *formattedNotification = [NSMutableDictionary dictionary]; + UNNotificationContent *content = notification.request.content; + + formattedNotification[@"identifier"] = notification.request.identifier; + + if (notification.date) { + NSDateFormatter *formatter = [NSDateFormatter new]; + [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"]; + NSString *dateString = [formatter stringFromDate:notification.date]; + formattedNotification[@"fireDate"] = dateString; + } + + formattedNotification[@"alertTitle"] = RCTNullIfNil(content.title); + formattedNotification[@"alertBody"] = RCTNullIfNil(content.body); + formattedNotification[@"category"] = RCTNullIfNil(content.categoryIdentifier); + formattedNotification[@"thread-id"] = RCTNullIfNil(content.threadIdentifier); + formattedNotification[@"userInfo"] = RCTNullIfNil(RCTJSONClean(content.userInfo)); + + return formattedNotification; +} + @interface RNNotifications () @property (nonatomic, strong) NSMutableDictionary *remoteNotificationCallbacks; @end @@ -146,6 +176,11 @@ - (void)setBridge:(RCTBridge *)bridge name:RNNotificationsRegistered object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(handleNotificationsRegistrationFailed:) + name:RNNotificationsRegistrationFailed + object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePushKitRegistered:) name:RNPushKitRegistered @@ -172,7 +207,8 @@ - (void)setBridge:(RCTBridge *)bridge object:nil]; [RNNotificationsBridgeQueue sharedInstance].openedRemoteNotification = [_bridge.launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]; - [RNNotificationsBridgeQueue sharedInstance].openedLocalNotification = [_bridge.launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; + UILocalNotification *localNotification = [_bridge.launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; + [RNNotificationsBridgeQueue sharedInstance].openedLocalNotification = localNotification ? localNotification.userInfo : nil; } /* @@ -185,11 +221,18 @@ + (void)didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notifi } } -+ (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken ++ (void)didRegisterForRemoteNotificationsWithDeviceToken:(id)deviceToken { + NSString *tokenRepresentation = [deviceToken isKindOfClass:[NSString class]] ? deviceToken : [self deviceTokenToString:deviceToken]; [[NSNotificationCenter defaultCenter] postNotificationName:RNNotificationsRegistered object:self - userInfo:@{@"deviceToken": [self deviceTokenToString:deviceToken]}]; + userInfo:@{@"deviceToken": tokenRepresentation}]; +} + ++ (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { + [[NSNotificationCenter defaultCenter] postNotificationName:RNNotificationsRegistrationFailed + object:self + userInfo:@{@"code": [NSNumber numberWithInteger:error.code], @"domain": error.domain, @"localizedDescription": error.localizedDescription}]; } @@ -485,6 +528,11 @@ - (void)handleNotificationsRegistered:(NSNotification *)notification [_bridge.eventDispatcher sendDeviceEventWithName:@"remoteNotificationsRegistered" body:notification.userInfo]; } +- (void)handleNotificationsRegistrationFailed:(NSNotification *)notification +{ + [_bridge.eventDispatcher sendDeviceEventWithName:@"remoteNotificationsRegistrationFailed" body:notification.userInfo]; +} + - (void)handlePushKitRegistered:(NSNotification *)notification { [_bridge.eventDispatcher sendDeviceEventWithName:@"pushKitRegistered" body:notification.userInfo]; @@ -562,6 +610,17 @@ - (void)handleNotificationActionTriggered:(NSNotification *)notification [RNNotifications requestPermissionsWithCategories:categories]; } +RCT_EXPORT_METHOD(getInitialNotification:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) +{ + NSDictionary * notification = nil; + notification = [RNNotificationsBridgeQueue sharedInstance].openedRemoteNotification ? + [RNNotificationsBridgeQueue sharedInstance].openedRemoteNotification : + [RNNotificationsBridgeQueue sharedInstance].openedLocalNotification; + [RNNotificationsBridgeQueue sharedInstance].openedRemoteNotification = nil; + [RNNotificationsBridgeQueue sharedInstance].openedLocalNotification = nil; + resolve(notification); +} + RCT_EXPORT_METHOD(log:(NSString *)message) { NSLog(message); @@ -582,6 +641,17 @@ - (void)handleNotificationActionTriggered:(NSNotification *)notification [RNNotifications registerPushKit]; } +RCT_EXPORT_METHOD(getBadgesCount:(RCTResponseSenderBlock)callback) +{ + NSInteger count = [UIApplication sharedApplication].applicationIconBadgeNumber; + callback(@[ [NSNumber numberWithInteger:count] ]); +} + +RCT_EXPORT_METHOD(setBadgesCount:(int)count) +{ + [[UIApplication sharedApplication] setApplicationIconBadgeNumber:count]; +} + RCT_EXPORT_METHOD(backgroundTimeRemaining:(RCTResponseSenderBlock)callback) { NSTimeInterval remainingTime = [UIApplication sharedApplication].backgroundTimeRemaining; @@ -602,43 +672,55 @@ - (void)handleNotificationActionTriggered:(NSNotification *)notification // Push background notifications to JS [[RNNotificationsBridgeQueue sharedInstance] consumeNotificationsQueue:^(NSDictionary* notification) { - [RNNotifications didReceiveRemoteNotification:notification]; + [RNNotifications didReceiveNotificationOnBackgroundState:notification]; }]; // Push opened local notifications NSDictionary* openedLocalNotification = [RNNotificationsBridgeQueue sharedInstance].openedLocalNotification; if (openedLocalNotification) { + [RNNotificationsBridgeQueue sharedInstance].openedLocalNotification = nil; [RNNotifications didNotificationOpen:openedLocalNotification]; } // Push opened remote notifications NSDictionary* openedRemoteNotification = [RNNotificationsBridgeQueue sharedInstance].openedRemoteNotification; if (openedRemoteNotification) { + [RNNotificationsBridgeQueue sharedInstance].openedRemoteNotification = nil; [RNNotifications didNotificationOpen:openedRemoteNotification]; } } RCT_EXPORT_METHOD(localNotification:(NSDictionary *)notification withId:(NSString *)notificationId) { - UILocalNotification* localNotification = [RCTConvert UILocalNotification:notification]; - NSMutableArray* userInfo = localNotification.userInfo.mutableCopy; - [userInfo setValue:notificationId forKey:@"__id"]; - localNotification.userInfo = userInfo; - - if ([notification objectForKey:@"fireDate"] != nil) { - [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; + if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10")) { + UNNotificationRequest* localNotification = [RCTConvert UNNotificationRequest:notification withId:notificationId]; + [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:localNotification withCompletionHandler:nil]; } else { - [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification]; + UILocalNotification* localNotification = [RCTConvert UILocalNotification:notification]; + NSMutableArray* userInfo = localNotification.userInfo.mutableCopy; + [userInfo setValue:notificationId forKey:@"__id"]; + localNotification.userInfo = userInfo; + + if ([notification objectForKey:@"fireDate"] != nil) { + [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; + } else { + [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification]; + } } } RCT_EXPORT_METHOD(cancelLocalNotification:(NSString *)notificationId) { - for (UILocalNotification* notification in [UIApplication sharedApplication].scheduledLocalNotifications) { - NSDictionary* notificationInfo = notification.userInfo; + if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10")) { + UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; + [center removePendingNotificationRequestsWithIdentifiers:@[notificationId]]; + } else { + for (UILocalNotification* notification in [UIApplication sharedApplication].scheduledLocalNotifications) { + NSDictionary* notificationInfo = notification.userInfo; - if ([[notificationInfo objectForKey:@"__id"] isEqualToString:notificationId]) { - [[UIApplication sharedApplication] cancelLocalNotification:notification]; + if ([[notificationInfo objectForKey:@"__id"] isEqualToString:notificationId]) { + [[UIApplication sharedApplication] cancelLocalNotification:notification]; + } } } } @@ -648,4 +730,62 @@ - (void)handleNotificationActionTriggered:(NSNotification *)notification [RCTSharedApplication() cancelAllLocalNotifications]; } +RCT_EXPORT_METHOD(isRegisteredForRemoteNotifications:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) +{ + BOOL ans; + + if (TARGET_IPHONE_SIMULATOR) { + ans = [[[UIApplication sharedApplication] currentUserNotificationSettings] types] != 0; + } + else { + ans = [[UIApplication sharedApplication] isRegisteredForRemoteNotifications]; + } + resolve(@(ans)); +} + +RCT_EXPORT_METHOD(checkPermissions:(RCTPromiseResolveBlock) resolve + reject:(RCTPromiseRejectBlock) reject) { + UIUserNotificationSettings *currentSettings = [[UIApplication sharedApplication] currentUserNotificationSettings]; + resolve(@{ + @"badge": @((currentSettings.types & UIUserNotificationTypeBadge) > 0), + @"sound": @((currentSettings.types & UIUserNotificationTypeSound) > 0), + @"alert": @((currentSettings.types & UIUserNotificationTypeAlert) > 0), + }); +} + +#if !TARGET_OS_TV + +RCT_EXPORT_METHOD(removeAllDeliveredNotifications) +{ + if ([UNUserNotificationCenter class]) { + UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; + [center removeAllDeliveredNotifications]; + } +} + +RCT_EXPORT_METHOD(removeDeliveredNotifications:(NSArray *)identifiers) +{ + if ([UNUserNotificationCenter class]) { + UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; + [center removeDeliveredNotificationsWithIdentifiers:identifiers]; + } +} + +RCT_EXPORT_METHOD(getDeliveredNotifications:(RCTResponseSenderBlock)callback) +{ + if ([UNUserNotificationCenter class]) { + UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; + [center getDeliveredNotificationsWithCompletionHandler:^(NSArray * _Nonnull notifications) { + NSMutableArray *formattedNotifications = [NSMutableArray new]; + + for (UNNotification *notification in notifications) { + [formattedNotifications addObject:RCTFormatUNNotification(notification)]; + } + callback(@[formattedNotifications]); + }]; + } +} + +#endif !TARGET_OS_TV + @end diff --git a/android/build.gradle b/android/build.gradle index 01d52837a..95ca5cdb9 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -1,12 +1,26 @@ +buildscript { + repositories { + maven { + url "https://maven.google.com" + } + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:3.0.1' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + apply plugin: 'com.android.library' android { - compileSdkVersion 26 - buildToolsVersion "26.0.2" + compileSdkVersion 27 defaultConfig { minSdkVersion 16 - targetSdkVersion 26 + targetSdkVersion 27 versionCode 1 versionName "1.0" } @@ -20,13 +34,12 @@ android { dependencies { // Google's GCM. - compile 'com.google.android.gms:play-services-gcm:11.6.0' - - compile 'com.facebook.react:react-native:+' + api "com.google.firebase:firebase-messaging:17.3.4" + implementation 'com.facebook.react:react-native:+' - compile 'me.leolin:ShortcutBadger:1.1.8@aar' + implementation 'me.leolin:ShortcutBadger:1.1.8@aar' - testCompile 'junit:junit:4.12' - testCompile 'org.mockito:mockito-core:2.+' - testCompile 'org.robolectric:robolectric:3.1.4' + testImplementation 'junit:junit:4.12' + testImplementation 'org.mockito:mockito-core:2.+' + testImplementation 'org.robolectric:robolectric:3.1.4' } diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml index 8061e77c1..ffef75f23 100644 --- a/android/src/main/AndroidManifest.xml +++ b/android/src/main/AndroidManifest.xml @@ -11,6 +11,9 @@ android:protectionLevel="signature" /> + + + - - - - - - - - - + android:name=".gcm.FcmInstanceIdListenerService"> - - - - - - - + + + diff --git a/android/src/main/java/com/wix/reactnativenotifications/Defs.java b/android/src/main/java/com/wix/reactnativenotifications/Defs.java index fff51742c..26a8b7a03 100644 --- a/android/src/main/java/com/wix/reactnativenotifications/Defs.java +++ b/android/src/main/java/com/wix/reactnativenotifications/Defs.java @@ -7,5 +7,6 @@ public interface Defs { String TOKEN_RECEIVED_EVENT_NAME = "remoteNotificationsRegistered"; String NOTIFICATION_RECEIVED_EVENT_NAME = "notificationReceived"; + String NOTIFICATION_RECEIVED_FOREGROUND_EVENT_NAME = "notificationReceivedInForeground"; String NOTIFICATION_OPENED_EVENT_NAME = "notificationOpened"; } diff --git a/android/src/main/java/com/wix/reactnativenotifications/RNNotificationsModule.java b/android/src/main/java/com/wix/reactnativenotifications/RNNotificationsModule.java index 0b4ef8a98..b3a68d6ff 100644 --- a/android/src/main/java/com/wix/reactnativenotifications/RNNotificationsModule.java +++ b/android/src/main/java/com/wix/reactnativenotifications/RNNotificationsModule.java @@ -5,6 +5,7 @@ import android.content.Context; import android.content.Intent; import android.os.Bundle; +import android.support.v4.app.NotificationManagerCompat; import android.util.Log; import com.facebook.react.bridge.Arguments; @@ -22,18 +23,18 @@ import com.wix.reactnativenotifications.core.notificationdrawer.IPushNotificationsDrawer; import com.wix.reactnativenotifications.core.notificationdrawer.PushNotificationsDrawer; import com.wix.reactnativenotifications.core.ReactAppLifecycleFacade; -import com.wix.reactnativenotifications.gcm.GcmInstanceIdRefreshHandlerService; +import com.wix.reactnativenotifications.gcm.FcmInstanceIdRefreshHandlerService; import com.wix.reactnativenotifications.helpers.ApplicationBadgeHelper; import static com.wix.reactnativenotifications.Defs.LOGTAG; public class RNNotificationsModule extends ReactContextBaseJavaModule implements AppLifecycleFacade.AppVisibilityListener, Application.ActivityLifecycleCallbacks { - public RNNotificationsModule(Application application, ReactApplicationContext reactContext) { + public RNNotificationsModule(Application application, RNNotificationsNativeCallback nativeCallback, ReactApplicationContext reactContext) { super(reactContext); if (AppLifecycleFacadeHolder.get() instanceof ReactAppLifecycleFacade) { - ((ReactAppLifecycleFacade) AppLifecycleFacadeHolder.get()).init(reactContext); + ((ReactAppLifecycleFacade) AppLifecycleFacadeHolder.get()).init(reactContext, nativeCallback); } AppLifecycleFacadeHolder.get().addVisibilityListener(this); application.registerActivityLifecycleCallbacks(this); @@ -47,7 +48,7 @@ public String getName() { @Override public void initialize() { Log.d(LOGTAG, "Native module init"); - startGcmIntentService(GcmInstanceIdRefreshHandlerService.EXTRA_IS_APP_INIT); + startGcmIntentService(FcmInstanceIdRefreshHandlerService.EXTRA_IS_APP_INIT); final IPushNotificationsDrawer notificationsDrawer = PushNotificationsDrawer.get(getReactApplicationContext().getApplicationContext()); notificationsDrawer.onAppInit(); @@ -56,7 +57,7 @@ public void initialize() { @ReactMethod public void refreshToken() { Log.d(LOGTAG, "Native method invocation: refreshToken()"); - startGcmIntentService(GcmInstanceIdRefreshHandlerService.EXTRA_MANUAL_REFRESH); + startGcmIntentService(FcmInstanceIdRefreshHandlerService.EXTRA_MANUAL_REFRESH); } @ReactMethod @@ -99,6 +100,12 @@ public void cancelLocalNotification(int notificationId) { notificationsDrawer.onNotificationClearRequest(notificationId); } + @ReactMethod + public void isRegisteredForRemoteNotifications(Promise promise) { + boolean hasPermission = NotificationManagerCompat.from(getReactApplicationContext()).areNotificationsEnabled(); + promise.resolve(new Boolean(hasPermission)); + } + @Override public void onAppVisible() { final IPushNotificationsDrawer notificationsDrawer = PushNotificationsDrawer.get(getReactApplicationContext().getApplicationContext()); @@ -141,7 +148,7 @@ public void onActivityDestroyed(Activity activity) { protected void startGcmIntentService(String extraFlag) { final Context appContext = getReactApplicationContext().getApplicationContext(); - final Intent tokenFetchIntent = new Intent(appContext, GcmInstanceIdRefreshHandlerService.class); + final Intent tokenFetchIntent = new Intent(appContext, FcmInstanceIdRefreshHandlerService.class); tokenFetchIntent.putExtra(extraFlag, true); appContext.startService(tokenFetchIntent); } diff --git a/android/src/main/java/com/wix/reactnativenotifications/RNNotificationsNativeCallback.java b/android/src/main/java/com/wix/reactnativenotifications/RNNotificationsNativeCallback.java new file mode 100644 index 000000000..8aabee048 --- /dev/null +++ b/android/src/main/java/com/wix/reactnativenotifications/RNNotificationsNativeCallback.java @@ -0,0 +1,7 @@ +package com.wix.reactnativenotifications; + +import com.facebook.react.bridge.WritableMap; + +public interface RNNotificationsNativeCallback { + void onEventNotSentToJS(String eventName, WritableMap data); +} diff --git a/android/src/main/java/com/wix/reactnativenotifications/RNNotificationsPackage.java b/android/src/main/java/com/wix/reactnativenotifications/RNNotificationsPackage.java index 923f0caf8..7fd65d2f9 100644 --- a/android/src/main/java/com/wix/reactnativenotifications/RNNotificationsPackage.java +++ b/android/src/main/java/com/wix/reactnativenotifications/RNNotificationsPackage.java @@ -3,7 +3,6 @@ import android.app.Application; import com.facebook.react.ReactPackage; -import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; @@ -14,21 +13,20 @@ public class RNNotificationsPackage implements ReactPackage { - - final Application mApplication; + private final Application mApplication; + private RNNotificationsNativeCallback mNativeCallback; public RNNotificationsPackage(Application application) { mApplication = application; } - @Override - public List createNativeModules(ReactApplicationContext reactContext) { - return Arrays.asList(new RNNotificationsModule(mApplication, reactContext)); + public void addNativeCallback(RNNotificationsNativeCallback rnNotificationsNativeCallback) { + mNativeCallback = rnNotificationsNativeCallback; } - // Deprecated RN 0.47 - public List> createJSModules() { - return Collections.emptyList(); + @Override + public List createNativeModules(ReactApplicationContext reactContext) { + return Arrays.asList(new RNNotificationsModule(mApplication, mNativeCallback, reactContext)); } @Override diff --git a/android/src/main/java/com/wix/reactnativenotifications/core/AppLifecycleFacade.java b/android/src/main/java/com/wix/reactnativenotifications/core/AppLifecycleFacade.java index bba1e91ba..508ba6fb9 100644 --- a/android/src/main/java/com/wix/reactnativenotifications/core/AppLifecycleFacade.java +++ b/android/src/main/java/com/wix/reactnativenotifications/core/AppLifecycleFacade.java @@ -1,5 +1,6 @@ package com.wix.reactnativenotifications.core; +import com.wix.reactnativenotifications.RNNotificationsNativeCallback; import com.facebook.react.bridge.ReactContext; public interface AppLifecycleFacade { @@ -11,6 +12,7 @@ interface AppVisibilityListener { boolean isReactInitialized(); ReactContext getRunningReactContext(); + RNNotificationsNativeCallback getNativeCallback(); boolean isAppVisible(); void addVisibilityListener(AppVisibilityListener listener); void removeVisibilityListener(AppVisibilityListener listener); diff --git a/android/src/main/java/com/wix/reactnativenotifications/core/JsIOHelper.java b/android/src/main/java/com/wix/reactnativenotifications/core/JsIOHelper.java index 4d8f4d1d5..cc460af6a 100644 --- a/android/src/main/java/com/wix/reactnativenotifications/core/JsIOHelper.java +++ b/android/src/main/java/com/wix/reactnativenotifications/core/JsIOHelper.java @@ -1,5 +1,6 @@ package com.wix.reactnativenotifications.core; +import com.wix.reactnativenotifications.RNNotificationsNativeCallback; import android.os.Bundle; import com.facebook.react.bridge.Arguments; @@ -8,18 +9,18 @@ import com.facebook.react.modules.core.DeviceEventManagerModule; public class JsIOHelper { - public boolean sendEventToJS(String eventName, Bundle data, ReactContext reactContext) { - if (reactContext != null) { - sendEventToJS(eventName, Arguments.fromBundle(data), reactContext); - return true; - } - return false; + public boolean sendEventToJS(String eventName, Bundle data, AppLifecycleFacade appLifecycleFacade) { + return sendEventToJS(eventName, Arguments.fromBundle(data), appLifecycleFacade); } - public boolean sendEventToJS(String eventName, WritableMap data, ReactContext reactContext) { - if (reactContext != null) { + public boolean sendEventToJS(String eventName, WritableMap data, AppLifecycleFacade appLifecycleFacade) { + RNNotificationsNativeCallback nativeCallback = appLifecycleFacade.getNativeCallback(); + ReactContext reactContext = appLifecycleFacade.getRunningReactContext(); + if (appLifecycleFacade.isReactInitialized() && reactContext != null) { reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, data); return true; + } else if (nativeCallback != null) { + nativeCallback.onEventNotSentToJS(eventName, data); } return false; } diff --git a/android/src/main/java/com/wix/reactnativenotifications/core/NotificationIntentAdapter.java b/android/src/main/java/com/wix/reactnativenotifications/core/NotificationIntentAdapter.java index 0413e2f86..3a2e65fe3 100644 --- a/android/src/main/java/com/wix/reactnativenotifications/core/NotificationIntentAdapter.java +++ b/android/src/main/java/com/wix/reactnativenotifications/core/NotificationIntentAdapter.java @@ -8,12 +8,14 @@ import com.wix.reactnativenotifications.core.notification.PushNotificationProps; public class NotificationIntentAdapter { - private static final int PENDING_INTENT_CODE = 0; private static final String PUSH_NOTIFICATION_EXTRA_NAME = "pushNotification"; public static PendingIntent createPendingNotificationIntent(Context appContext, Intent intent, PushNotificationProps notification) { intent.putExtra(PUSH_NOTIFICATION_EXTRA_NAME, notification.asBundle()); - return PendingIntent.getService(appContext, PENDING_INTENT_CODE, intent, PendingIntent.FLAG_ONE_SHOT); + // a unique action, data, type, class, or category must be set, otherwise the intent matcher + // gets confused see https://developer.android.com/reference/android/app/PendingIntent + intent.setAction(String.valueOf(System.currentTimeMillis())); + return PendingIntent.getService(appContext, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_ONE_SHOT); } public static Bundle extractPendingNotificationDataFromIntent(Intent intent) { diff --git a/android/src/main/java/com/wix/reactnativenotifications/core/ReactAppLifecycleFacade.java b/android/src/main/java/com/wix/reactnativenotifications/core/ReactAppLifecycleFacade.java index b185903e6..838c4c19c 100644 --- a/android/src/main/java/com/wix/reactnativenotifications/core/ReactAppLifecycleFacade.java +++ b/android/src/main/java/com/wix/reactnativenotifications/core/ReactAppLifecycleFacade.java @@ -1,5 +1,6 @@ package com.wix.reactnativenotifications.core; +import com.wix.reactnativenotifications.RNNotificationsNativeCallback; import android.util.Log; import com.facebook.react.bridge.LifecycleEventListener; @@ -14,10 +15,12 @@ public class ReactAppLifecycleFacade implements AppLifecycleFacade { private ReactContext mReactContext; private boolean mIsVisible; + private RNNotificationsNativeCallback mNativeCallback; private Set mListeners = new CopyOnWriteArraySet<>(); - public void init(ReactContext reactContext) { + public void init(ReactContext reactContext, RNNotificationsNativeCallback nativeCallback) { mReactContext = reactContext; + mNativeCallback = nativeCallback; reactContext.addLifecycleEventListener(new LifecycleEventListener() { @Override public void onHostResume() { @@ -58,6 +61,11 @@ public ReactContext getRunningReactContext() { return mReactContext; } + @Override + public RNNotificationsNativeCallback getNativeCallback() { + return mNativeCallback; + } + @Override public boolean isAppVisible() { return mIsVisible; diff --git a/android/src/main/java/com/wix/reactnativenotifications/core/notification/PushNotification.java b/android/src/main/java/com/wix/reactnativenotifications/core/notification/PushNotification.java index fe82ee1d0..0f136715f 100644 --- a/android/src/main/java/com/wix/reactnativenotifications/core/notification/PushNotification.java +++ b/android/src/main/java/com/wix/reactnativenotifications/core/notification/PushNotification.java @@ -28,6 +28,7 @@ import static com.wix.reactnativenotifications.Defs.NOTIFICATION_OPENED_EVENT_NAME; import static com.wix.reactnativenotifications.Defs.NOTIFICATION_RECEIVED_EVENT_NAME; +import static com.wix.reactnativenotifications.Defs.NOTIFICATION_RECEIVED_FOREGROUND_EVENT_NAME; public class PushNotification implements IPushNotification { @@ -79,12 +80,14 @@ public void onReceivedLocal(Integer notificationId) throws InvalidNotificationEx postNotification(notificationId); } notifyReceivedToJS(); + if (mAppLifecycleFacade.isAppVisible()) { + notifiyReceivedForegroundNotificationToJS(); + } } @Override public void onOpened() { digestNotification(); - clearAllNotifications(); } @Override @@ -198,15 +201,19 @@ protected Notification.Builder getNotificationBuilder(PendingIntent intent) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { notificationBuilder = new Notification.Builder(mContext); } else { + createNotificationChannel(); // Must happen before notifying system of notification. notificationBuilder = new Notification.Builder(mContext, mNotificationProps.getChannelId()); } notificationBuilder.setContentTitle(title) .setContentText(mNotificationProps.getBody()) + .setStyle(new Notification.BigTextStyle() + .bigText(mNotificationProps.getBody())) .setPriority(mNotificationProps.getPriority()) .setContentIntent(intent) .setVibrate(mNotificationProps.getVibrationPattern()) .setSmallIcon(smallIconResId) + .setShowWhen(true) .setAutoCancel(true); int badge = mNotificationProps.getBadge(); @@ -214,8 +221,6 @@ protected Notification.Builder getNotificationBuilder(PendingIntent intent) { notificationBuilder.setNumber(badge); } - createNotificationChannel(); // Must happen before notifying system of notification. - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { notificationBuilder.setColor(Color.parseColor("#f65335")); } @@ -305,11 +310,15 @@ protected int createNotificationId(Notification notification) { } private void notifyReceivedToJS() { - mJsIOHelper.sendEventToJS(NOTIFICATION_RECEIVED_EVENT_NAME, mNotificationProps.asBundle(), mAppLifecycleFacade.getRunningReactContext()); + mJsIOHelper.sendEventToJS(NOTIFICATION_RECEIVED_EVENT_NAME, mNotificationProps.asBundle(), mAppLifecycleFacade); + } + + private void notifiyReceivedForegroundNotificationToJS() { + mJsIOHelper.sendEventToJS(NOTIFICATION_RECEIVED_FOREGROUND_EVENT_NAME, mNotificationProps.asBundle(), mAppLifecycleFacade); } private void notifyOpenedToJS() { - mJsIOHelper.sendEventToJS(NOTIFICATION_OPENED_EVENT_NAME, mNotificationProps.asBundle(), mAppLifecycleFacade.getRunningReactContext()); + mJsIOHelper.sendEventToJS(NOTIFICATION_OPENED_EVENT_NAME, mNotificationProps.asBundle(), mAppLifecycleFacade); } protected void launchOrResumeApp() { diff --git a/android/src/main/java/com/wix/reactnativenotifications/core/notificationdrawer/PushNotificationsDrawer.java b/android/src/main/java/com/wix/reactnativenotifications/core/notificationdrawer/PushNotificationsDrawer.java index 7b320e16d..acd73c231 100644 --- a/android/src/main/java/com/wix/reactnativenotifications/core/notificationdrawer/PushNotificationsDrawer.java +++ b/android/src/main/java/com/wix/reactnativenotifications/core/notificationdrawer/PushNotificationsDrawer.java @@ -32,12 +32,16 @@ protected PushNotificationsDrawer(Context context, AppLaunchHelper appLaunchHelp @Override public void onAppInit() { - clearAll(); + /** + * No OP. + */ } @Override public void onAppVisible() { - clearAll(); + /** + * No OP. + */ } @Override @@ -51,7 +55,9 @@ public void onNewActivity(Activity activity) { @Override public void onNotificationOpened() { - clearAll(); + /** + * No OP. + */ } @Override diff --git a/android/src/main/java/com/wix/reactnativenotifications/gcm/GcmMessageHandlerService.java b/android/src/main/java/com/wix/reactnativenotifications/gcm/FcmInstanceIdListenerService.java similarity index 75% rename from android/src/main/java/com/wix/reactnativenotifications/gcm/GcmMessageHandlerService.java rename to android/src/main/java/com/wix/reactnativenotifications/gcm/FcmInstanceIdListenerService.java index 9482bb139..1f91d8715 100644 --- a/android/src/main/java/com/wix/reactnativenotifications/gcm/GcmMessageHandlerService.java +++ b/android/src/main/java/com/wix/reactnativenotifications/gcm/FcmInstanceIdListenerService.java @@ -4,21 +4,34 @@ import android.util.Log; import org.json.*; -import com.google.android.gms.gcm.GcmListenerService; +import com.facebook.common.logging.FLog; +import com.google.firebase.messaging.FirebaseMessagingService; +import com.google.firebase.messaging.RemoteMessage; import com.wix.reactnativenotifications.core.notification.IPushNotification; import com.wix.reactnativenotifications.core.notification.PushNotification; +import java.util.Map; + import static com.wix.reactnativenotifications.Defs.LOGTAG; -public class GcmMessageHandlerService extends GcmListenerService { +/** + * Instance-ID + token refreshing handling service. Contacts the GCM to fetch the updated token. + * + * @author amitd + */ +public class FcmInstanceIdListenerService extends FirebaseMessagingService { + + private final static String LOG_TAG = "GcmMessageHandlerService"; @Override - public void onMessageReceived(String s, Bundle bundle) { + public void onMessageReceived(RemoteMessage message){ + Map messageData = message.getData(); + Bundle bundle = convertMapToBundle(messageData); Log.d(LOGTAG, "New message from GCM: " + bundle); - String rawData = bundle.getString("data"); // Hack by Convoy, all of our data is nested in "data" json. We need to bring it up a level. // we could change this in API but it's backwards incompatible with current app to do so. - if (rawData.length() > 0) { + String rawData = bundle.getString("data"); + if (rawData != null && rawData.length() > 0) { try { JSONObject data = new JSONObject(rawData); try { @@ -72,6 +85,8 @@ public void onMessageReceived(String s, Bundle bundle) { } catch (JSONException ignored) { Log.d(LOGTAG, "Failed to parse raw data"); } + } else { + FLog.i(LOG_TAG, "rawData doesn't contain data key or data is empty: " + bundle); } try { @@ -80,6 +95,17 @@ public void onMessageReceived(String s, Bundle bundle) { } catch (IPushNotification.InvalidNotificationException e) { // A GCM message, yes - but not the kind we know how to work with. Log.v(LOGTAG, "GCM message handling aborted", e); + FLog.i(LOG_TAG, "GCM message handling aborted: " + bundle); } } + + private Bundle convertMapToBundle(Map map) { + Bundle bundle = new Bundle(); + for (Map.Entry entry : map.entrySet()) { + bundle.putString(entry.getKey(), entry.getValue()); + } + + return bundle; + } + } diff --git a/android/src/main/java/com/wix/reactnativenotifications/gcm/GcmInstanceIdRefreshHandlerService.java b/android/src/main/java/com/wix/reactnativenotifications/gcm/FcmInstanceIdRefreshHandlerService.java similarity index 74% rename from android/src/main/java/com/wix/reactnativenotifications/gcm/GcmInstanceIdRefreshHandlerService.java rename to android/src/main/java/com/wix/reactnativenotifications/gcm/FcmInstanceIdRefreshHandlerService.java index 3aa7aa9dc..8270ad68e 100644 --- a/android/src/main/java/com/wix/reactnativenotifications/gcm/GcmInstanceIdRefreshHandlerService.java +++ b/android/src/main/java/com/wix/reactnativenotifications/gcm/FcmInstanceIdRefreshHandlerService.java @@ -3,18 +3,18 @@ import android.app.IntentService; import android.content.Intent; -public class GcmInstanceIdRefreshHandlerService extends IntentService { +public class FcmInstanceIdRefreshHandlerService extends IntentService { public static String EXTRA_IS_APP_INIT = "isAppInit"; public static String EXTRA_MANUAL_REFRESH = "doManualRefresh"; - public GcmInstanceIdRefreshHandlerService() { - super(GcmInstanceIdRefreshHandlerService.class.getSimpleName()); + public FcmInstanceIdRefreshHandlerService() { + super(FcmInstanceIdRefreshHandlerService.class.getSimpleName()); } @Override protected void onHandleIntent(Intent intent) { - IGcmToken gcmToken = GcmToken.get(this); + IFcmToken gcmToken = FcmToken.get(this); if (gcmToken == null) { return; } diff --git a/android/src/main/java/com/wix/reactnativenotifications/gcm/FcmToken.java b/android/src/main/java/com/wix/reactnativenotifications/gcm/FcmToken.java new file mode 100644 index 000000000..6b8a04fec --- /dev/null +++ b/android/src/main/java/com/wix/reactnativenotifications/gcm/FcmToken.java @@ -0,0 +1,110 @@ +package com.wix.reactnativenotifications.gcm; + +import android.content.Context; +import android.os.Handler; +import android.os.Looper; +import android.util.Log; + +import com.facebook.react.ReactApplication; +import com.facebook.react.ReactInstanceManager; +import com.facebook.react.bridge.ReactContext; +import com.facebook.react.modules.core.DeviceEventManagerModule; +import com.google.android.gms.tasks.OnSuccessListener; +import com.google.firebase.iid.FirebaseInstanceId; +import com.google.firebase.iid.InstanceIdResult; + +import static com.wix.reactnativenotifications.Defs.LOGTAG; +import static com.wix.reactnativenotifications.Defs.TOKEN_RECEIVED_EVENT_NAME; + +public class FcmToken implements IFcmToken { + + final protected Context mAppContext; + + protected static String sToken; + + private final Runnable sendTokenToJsRunnable = new Runnable() { + @Override + public void run() { + synchronized (mAppContext) { + final ReactInstanceManager instanceManager = ((ReactApplication) mAppContext).getReactNativeHost().getReactInstanceManager(); + final ReactContext reactContext = instanceManager.getCurrentReactContext(); + // Note: Cannot assume react-context exists cause this is an async dispatched service. + if (reactContext != null && reactContext.hasActiveCatalystInstance()) { + reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(TOKEN_RECEIVED_EVENT_NAME, sToken); + } + } + } + }; + + private final Handler mainThreadHandler = new Handler(Looper.getMainLooper()); + + protected FcmToken(Context appContext) { + if (!(appContext instanceof ReactApplication)) { + throw new IllegalStateException("Application instance isn't a react-application"); + } + mAppContext = appContext; + } + + public static IFcmToken get(Context context) { + Context appContext = context.getApplicationContext(); + if (appContext instanceof INotificationsGcmApplication) { + return ((INotificationsGcmApplication) appContext).getFcmToken(context); + } + return new FcmToken(appContext); + } + + @Override + public void onNewTokenReady() { + synchronized (mAppContext) { + refreshToken(); + } + } + + @Override + public void onManualRefresh() { + synchronized (mAppContext) { + if (sToken == null) { + Log.i(LOGTAG, "Manual token refresh => asking for new token"); + refreshToken(); + } else { + Log.i(LOGTAG, "Manual token refresh => publishing existing token ("+sToken+")"); + sendTokenToJS(); + } + } + } + + @Override + public void onAppReady() { + synchronized (mAppContext) { + if (sToken == null) { + Log.i(LOGTAG, "App initialized => asking for new token"); + refreshToken(); + } else { + // Except for first run, this should be the case. + Log.i(LOGTAG, "App initialized => publishing existing token ("+sToken+")"); + sendTokenToJS(); + } + } + } + + protected void refreshToken() { + FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( new OnSuccessListener() { + @Override + public void onSuccess(InstanceIdResult instanceIdResult) { + sToken = instanceIdResult.getToken(); + Log.i(LOGTAG, "FCM has a new token" + "=" + sToken); + sendTokenToJS(); + } + }); + } + + /** + * This method can be called from a background thread. The call to getReactInstanceManager() + * can end up calling createReactInstanceManager() which must be called from the UI thread. + * + * Because of this restriction we make a point to always post this runnable to a main thread. + */ + protected void sendTokenToJS() { + mainThreadHandler.post(sendTokenToJsRunnable); + } +} diff --git a/android/src/main/java/com/wix/reactnativenotifications/gcm/GcmInstanceIdListenerService.java b/android/src/main/java/com/wix/reactnativenotifications/gcm/GcmInstanceIdListenerService.java deleted file mode 100644 index 933415f5c..000000000 --- a/android/src/main/java/com/wix/reactnativenotifications/gcm/GcmInstanceIdListenerService.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.wix.reactnativenotifications.gcm; - -import android.content.Intent; - -import com.google.android.gms.iid.InstanceIDListenerService; - -/** - * Instance-ID + token refreshing handling service. Contacts the GCM to fetch the updated token. - * - * @author amitd - */ -public class GcmInstanceIdListenerService extends InstanceIDListenerService { - - @Override - public void onTokenRefresh() { - // Fetch updated Instance ID token and notify our app's server of any changes (if applicable). - // Google recommends running this from an intent service. - Intent intent = new Intent(this, GcmInstanceIdRefreshHandlerService.class); - startService(intent); - } -} diff --git a/android/src/main/java/com/wix/reactnativenotifications/gcm/GcmToken.java b/android/src/main/java/com/wix/reactnativenotifications/gcm/GcmToken.java deleted file mode 100644 index b11a6b5f4..000000000 --- a/android/src/main/java/com/wix/reactnativenotifications/gcm/GcmToken.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.wix.reactnativenotifications.gcm; - -import android.content.Context; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.support.annotation.NonNull; -import android.util.Log; - -import com.facebook.react.ReactApplication; -import com.facebook.react.ReactInstanceManager; -import com.facebook.react.bridge.ReactContext; -import com.facebook.react.modules.core.DeviceEventManagerModule; -import com.google.android.gms.gcm.GoogleCloudMessaging; -import com.google.android.gms.iid.InstanceID; - -import static com.wix.reactnativenotifications.Defs.GCM_SENDER_ID_ATTR_NAME; -import static com.wix.reactnativenotifications.Defs.LOGTAG; -import static com.wix.reactnativenotifications.Defs.TOKEN_RECEIVED_EVENT_NAME; - -public class GcmToken implements IGcmToken { - - final protected Context mAppContext; - - protected static String sToken; - - protected GcmToken(Context appContext) { - if (!(appContext instanceof ReactApplication)) { - throw new IllegalStateException("Application instance isn't a react-application"); - } - mAppContext = appContext; - } - - public static IGcmToken get(Context context) { - Context appContext = context.getApplicationContext(); - if (appContext instanceof INotificationsGcmApplication) { - return ((INotificationsGcmApplication) appContext).getGcmToken(context); - } - return new GcmToken(appContext); - } - - @Override - public void onNewTokenReady() { - synchronized (mAppContext) { - refreshToken(); - } - } - - @Override - public void onManualRefresh() { - synchronized (mAppContext) { - if (sToken == null) { - Log.i(LOGTAG, "Manual token refresh => asking for new token"); - refreshToken(); - } else { - Log.i(LOGTAG, "Manual token refresh => publishing existing token ("+sToken+")"); - sendTokenToJS(); - } - } - } - - @Override - public void onAppReady() { - synchronized (mAppContext) { - if (sToken == null) { - Log.i(LOGTAG, "App initialized => asking for new token"); - refreshToken(); - } else { - // Except for first run, this should be the case. - Log.i(LOGTAG, "App initialized => publishing existing token ("+sToken+")"); - sendTokenToJS(); - } - } - } - - protected void refreshToken() { - try { - sToken = getNewToken(); - } catch (Exception e) { - Log.e(LOGTAG, "Failed to retrieve new token", e); - return; - } - - sendTokenToJS(); - } - - @NonNull - protected String getNewToken() throws Exception { - final InstanceID instanceId = InstanceID.getInstance(mAppContext); - Log.d(LOGTAG, "GCM is refreshing token... instanceId=" + instanceId.getId()); - - // TODO why is this needed? - GoogleCloudMessaging.getInstance(mAppContext).close(); - - try { - final String registrationToken = instanceId.getToken(getSenderId(), GoogleCloudMessaging.INSTANCE_ID_SCOPE); - Log.i(LOGTAG, "GCM has a new token: instanceId=" + instanceId.getId() + ", token=" + registrationToken); - return registrationToken; - } catch (Exception e) { - throw new Exception("FATAL: Failed to fetch a fresh new token, instanceId=" + instanceId.getId(), e); - } - } - - protected String getSenderId() { - final String senderId = getSenderIdFromManifest(); - if (senderId == null) { - throw new IllegalStateException("Sender ID not found in manifest. Did you forget to add it as the value of a '"+GCM_SENDER_ID_ATTR_NAME+"' meta-data field?"); - } - return senderId; - } - - protected String getSenderIdFromManifest() { - final ApplicationInfo appInfo; - try { - appInfo = mAppContext.getPackageManager().getApplicationInfo(mAppContext.getPackageName(), PackageManager.GET_META_DATA); - return appInfo.metaData.getString(GCM_SENDER_ID_ATTR_NAME); - } catch (PackageManager.NameNotFoundException e) { - // Should REALLY never happen cause we're querying for our own package. - Log.e(LOGTAG, "Failed to resolve sender ID from manifest", e); - return null; - } - } - - protected void sendTokenToJS() { - final ReactInstanceManager instanceManager = ((ReactApplication) mAppContext).getReactNativeHost().getReactInstanceManager(); - final ReactContext reactContext = instanceManager.getCurrentReactContext(); - - // Note: Cannot assume react-context exists cause this is an async dispatched service. - if (reactContext != null && reactContext.hasActiveCatalystInstance()) { - reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(TOKEN_RECEIVED_EVENT_NAME, sToken); - } - } -} diff --git a/android/src/main/java/com/wix/reactnativenotifications/gcm/IGcmToken.java b/android/src/main/java/com/wix/reactnativenotifications/gcm/IFcmToken.java similarity index 95% rename from android/src/main/java/com/wix/reactnativenotifications/gcm/IGcmToken.java rename to android/src/main/java/com/wix/reactnativenotifications/gcm/IFcmToken.java index f324a591f..9e75d3901 100644 --- a/android/src/main/java/com/wix/reactnativenotifications/gcm/IGcmToken.java +++ b/android/src/main/java/com/wix/reactnativenotifications/gcm/IFcmToken.java @@ -1,6 +1,6 @@ package com.wix.reactnativenotifications.gcm; -public interface IGcmToken { +public interface IFcmToken { /** * Handle an event where we've been notified of a that a fresh token is now available from Google. diff --git a/android/src/main/java/com/wix/reactnativenotifications/gcm/INotificationsGcmApplication.java b/android/src/main/java/com/wix/reactnativenotifications/gcm/INotificationsGcmApplication.java index 36f59f71c..d318ecc4a 100644 --- a/android/src/main/java/com/wix/reactnativenotifications/gcm/INotificationsGcmApplication.java +++ b/android/src/main/java/com/wix/reactnativenotifications/gcm/INotificationsGcmApplication.java @@ -3,5 +3,5 @@ import android.content.Context; public interface INotificationsGcmApplication { - IGcmToken getGcmToken(Context context); + IFcmToken getFcmToken(Context context); } diff --git a/docs/advancedIos.md b/docs/advancedIos.md new file mode 100644 index 000000000..9e44bde67 --- /dev/null +++ b/docs/advancedIos.md @@ -0,0 +1,277 @@ +# Advanced API - iOS + +## Managed Notifications + +Managed notifications are notifications that can be cleared by a server request. +You can find this feature in facebook messenger, when you receive a message in your mobile, but open it in facebook web. More examples are Whatsapp web and gmail app. + +In order to handle managed notifications, your app must support background notifications, and the server should send the notifications you'd like to "manage" a bit differently. Let's start. + +First, enable the *Remote notifications* checkbox under **capabilities - Background Modes**: +![Background Modes](http://docs.urbanairship.com/_images/ios-background-push-capabilities1.png) + +Then, add the following lines to `info.plist`: + +```xml +UIBackgroundModes + + remote-notification + +``` + +That's it for the client side! + +Now the server should push the notification a bit differently- background instead of reguler. You should also provide the action (`CREATE` notification or `CLEAR` notification), and `notificationId` as a unique identifier of the notification. + +**Regular** notification payload: + +```javascript +{ + aps: { + alert: { + body: "This is regular notification" + }, + badge: 5, + sound: "chime.aiff", + } +} +``` + +**Managed** notification payload: + +```javascript +{ + aps: { + "content-available": 1 + }, + managedAps: { + action: "CREATE", // set it to "CLEAR" in order to clear the notification remotely + notificationId: "1234", // must be unique identifier + sound: "chime.aiff", + alert: { + body: "This is managed notification" + } + } +} +``` + +--- + +## Remove notifications + +### getDeliveredNotifications + +`PushNotification.getDeliveredNotifications(callback: (notifications: Array) => void)` + +Provides you with a list of the app’s notifications that are still displayed in Notification Center. + +### removeDeliveredNotifications + +`PushNotification.removeDeliveredNotifications(identifiers: Array)` + +Removes the specified notifications from Notification Center. + +### removeAllDeliveredNotifications + +`PushNotification.removeAllDeliveredNotifications()` + +Removes all delivered notifications from Notification Center. + +--- + +## PushKit API + +The PushKit framework provides the classes for your iOS apps to receive background pushes from remote servers. it has better support for background notifications compared to regular push notifications with `content-available: 1`. More info in [iOS PushKit documentation](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/PushKit_Framework/). + +### Register to PushKit +After [preparing your app to receive VoIP push notifications](https://developer.apple.com/library/ios/documentation/Performance/Conceptual/EnergyGuide-iOS/OptimizeVoIP.html), add the following lines to `appDelegate.m` in order to support PushKit events: + +```objective-c +#import "RNNotifications.h" +#import +``` + +And the following methods: + +```objective-c +// PushKit API Support +- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type +{ + [RNNotifications didUpdatePushCredentials:credentials forType:type]; +} + +- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type +{ + [RNNotifications didReceiveRemoteNotification:payload.dictionaryPayload]; +} +``` + +In your ReactNative code, add event handler for `pushKitRegistered` event and call to `registerPushKit()`: + +```javascript +constructor() { + NotificationsIOS.addEventListener('pushKitRegistered', this.onPushKitRegistered.bind(this)); + NotificationsIOS.registerPushKit(); +} + +onPushKitRegistered(deviceToken) { + console.log("PushKit Token Received: " + deviceToken); +} + +componentWillUnmount() { + // Don't forget to remove the event listeners to prevent memory leaks! + NotificationsIOS.removeEventListener('pushKitRegistered', onPushKitRegistered(this)); +} +``` + +> 1. Notice that PushKit device token and regular notifications device token are different, so you must handle two different tokens in the server side in order to support this feature. +> 2. PushKit will not request permissions from the user for push notifications. + + +--- + +## Interactive / Actionable Notifications + +> This section provides description for iOS. For notifications customization on Android, refer to [our wiki](https://github.com/wix/react-native-notifications/wiki/Android-Customizations#customizing-notifications-layout). + +Interactive notifications allow you to reply to a message right from the notification banner or take action right from the lock screen. + +On the Lock screen and within Notification Center, you swipe from right to left +to reveal actions. Destructive actions, like trashing an email, are color-coded red. Relatively neutral actions, like dismissing an alert or declining an invitation, are color-coded gray. + +For banners, you pull down to reveal actions as buttons. For popups, the actions are immediately visible — the buttons are right there. + +You can find more info about interactive notifications [here](http://www.imore.com/interactive-notifications-ios-8-explained). + +![Interactive Notifications](http://i.imgur.com/XrVzy9w.gif) + + +Notification **actions** allow the user to interact with a given notification. + +Notification **categories** allow you to group multiple actions together, and to connect the actions with the push notification itself. + +In order to support interactive notifications, firstly add the following methods to `appDelegate.m` file: + +```objective-c +// Required for the notification actions. +- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler +{ + [RNNotifications handleActionWithIdentifier:identifier forLocalNotification:notification withResponseInfo:responseInfo completionHandler:completionHandler]; +} + +- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler +{ + [RNNotifications handleActionWithIdentifier:identifier forRemoteNotification:userInfo withResponseInfo:responseInfo completionHandler:completionHandler]; +} +``` + +Then, follow the basic workflow of adding interactive notifications to your app: + +1. Config the actions. +2. Group actions together into categories. +3. Register to push notifications with the configured categories. +4. Push a notification (or trigger a [local](#triggering-local-notifications) one) with the configured category name. + +### Example +#### Config the Actions +We will config two actions: upvote and reply. + +```javascript +import NotificationsIOS, { NotificationAction, NotificationCategory } from 'react-native-notifications'; + +let upvoteAction = new NotificationAction({ + activationMode: "background", + title: String.fromCodePoint(0x1F44D), + identifier: "UPVOTE_ACTION" +}, (action, completed) => { + console.log("ACTION RECEIVED"); + console.log(JSON.stringify(action)); + + // You must call to completed(), otherwise the action will not be triggered + completed(); +}); + +let replyAction = new NotificationAction({ + activationMode: "background", + title: "Reply", + behavior: "textInput", + authenticationRequired: true, + identifier: "REPLY_ACTION" +}, (action, completed) => { + console.log("ACTION RECEIVED"); + console.log(action); + + completed(); +}); + +``` + +#### Config the Category +We will group `upvote` action and `reply` action into a single category: `EXAMPLE_CATEGORY `. If the notification contains `EXAMPLE_CATEGORY ` under `category` field, those actions will appear. + +```javascript +let exampleCategory = new NotificationCategory({ + identifier: "EXAMPLE_CATEGORY", + actions: [upvoteAction, replyAction], + context: "default" +}); +``` + +#### Register to Push Notifications +Instead of basic registration like we've done before, we will register the device to push notifications with the category we've just created. + +```javascript +NotificationsIOS.requestPermissions([exampleCategory]); +``` + +#### Push an Interactive Notification +Notification payload should look like this: + +```javascript +{ + aps: { + // ... (alert, sound, badge, etc) + category: "EXAMPLE_CATEGORY" + } +} +``` + +The [example app](https://github.com/wix/react-native-notifications/tree/master/example) contains this interactive notification example, you can follow there. + +### `NotificationAction` Payload + +- `title` - Action button title. +- `identifier` - Action identifier (must be unique). +- `activationMode` - Indicating whether the app should activate to the foreground or background. + - `foreground` (default) - Activate the app and put it in the foreground. + - `background` - Activate the app and put it in the background. If the app is already in the foreground, it remains in the foreground. +- `behavior` - Indicating additional behavior that the action supports. + - `default` - No additional behavior. + - `textInput` - When button is tapped, the action opens a text input. the text will be delivered to your action callback. +- `destructive` - A Boolean value indicating whether the action is destructive. When the value of this property is `true`, the system displays the corresponding button differently to indicate that the action is destructive. +- `authenticationRequired` - A Boolean value indicating whether the user must unlock the device before the action is performed. + +### `NotificationCategory` Payload + +- `identifier` - The name of the action group (must be unique). +- `actions` - An array of `NotificationAction` objects, which related to this category. +- `context` - Indicating the amount of space available for displaying actions in a notification. + - `default` (default) - Displayes up to 4 actions (full UI). + - `minimal` - Displays up tp 2 actions (minimal UI). + + +#### Get and set application icon badges count (iOS only) + +Get the current number: +```javascript +NotificationsIOS.getBadgesCount((count) => console.log(count)); +``` + +Set to specific number: +```javascript +NotificationsIOS.setBadgesCount(2); +``` +Clear badges icon: +```javascript +NotificationsIOS.setBadgesCount(0); +``` diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 000000000..12e33d02f --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,117 @@ +# Installation + +As with any React Native project, the first step is to add the project as an npm dependency. + +The 2nd is to do some platform specific setup so as to be able to work with Apple and Google's services for push notifications. + +Start by running this: + +``` +$ npm install react-native-notifications --save +``` + +## iOS + +First, [Manually link](https://facebook.github.io/react-native/docs/linking-libraries-ios.html#manual-linking) the library to your Xcode project. + +Then, to enable notifications support add the following line at the top of your `AppDelegate.m` + +```objective-c +#import "RNNotifications.h" +``` + +And the following methods to support registration and receiving notifications: + +```objective-c +// Required to register for notifications +- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings +{ + [RNNotifications didRegisterUserNotificationSettings:notificationSettings]; +} + +- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken +{ + [RNNotifications didRegisterForRemoteNotificationsWithDeviceToken:deviceToken]; +} + +- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { + [RNNotifications didFailToRegisterForRemoteNotificationsWithError:error]; +} + +// Required for the notification event. +- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification { + [RNNotifications didReceiveRemoteNotification:notification]; +} + +// Required for the localNotification event. +- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification +{ + [RNNotifications didReceiveLocalNotification:notification]; +} +``` + +## Android + + +Add a reference to the library's native code in your global `settings.gradle`: + +```gradle +include ':reactnativenotifications' +project(':reactnativenotifications').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-notifications/android') +``` + +Declare the library as a dependency in your **app-project's** `build.gradle`: + +```gradle +dependencies { + // ... + + compile project(':reactnativenotifications') +} +``` + +Add the library to your application class (e.g. `MainApplication.java`): + +```java +import com.wix.reactnativenotifications.RNNotificationsPackage; + +... + + @Override + protected List getPackages() { + return Arrays.asList( + new MainReactPackage(), + // ... + // Add this line: + new RNNotificationsPackage(MainApplication.this) + ); +``` + +### Receiving push notifications + +> Note: This section is only necessary in case you wish to be able to **receive** push notifications in your React-Native app. + +Push notifications on Android are managed and dispatched using [Google's GCM service](https://developers.google.com/cloud-messaging/gcm) (now integrated into Firebase). The following installation steps are a TL;DR of [Google's GCM setup guide](https://developers.google.com/cloud-messaging/android/client). You can follow them to get GCM integrated quickly, but we recommend that you will in the very least have a peek at the guide's overview. + +#### Step #1: Subscribe to Google's GCM + +To set GCM in your app, you must first create a Google API-project and obtain a **Sender ID** and a **Server API Key**. If you have no existing API project yet, the easiest way to go about in creating one is using [this step-by-step installation process](https://developers.google.com/mobile/add); Use [this tutorial](https://code.tutsplus.com/tutorials/how-to-get-started-with-push-notifications-on-android--cms-25870) for insturctions. + +Alternatively, follow [Google's complete guide](https://developers.google.com/cloud-messaging/android/client#create-an-api-project). + +#### Step #2: Add Sender ID to Manifest File + +Once obtained, bundle the Sender ID onto your main `manifest.xml` file: + +```gradle + +... + + ... + // Replace '1234567890' with your sender ID. + // IMPORTANT: Leave the trailing \0 intact!!! + + + + +``` diff --git a/docs/localNotifications.md b/docs/localNotifications.md new file mode 100644 index 000000000..9747146c6 --- /dev/null +++ b/docs/localNotifications.md @@ -0,0 +1,84 @@ + +# Local Notifications + +## iOS + +You can manually trigger local notifications in your JS code, to be posted immediately or in the future. +Triggering local notifications is fully compatible with React Native `PushNotificationsIOS` library. + +Example: + +```javascript +let localNotification = NotificationsIOS.localNotification({ + alertBody: "Local notificiation!", + alertTitle: "Local Notification Title", + soundName: "chime.aiff", + silent: false, + category: "SOME_CATEGORY", + userInfo: { } +}); +``` + +Notification object contains: + +- **`fireDate`**- The date and time when the system should deliver the notification (optinal - default is immidiate dispatch). +- `alertBody`- The message displayed in the notification alert. +- `alertTitle`- The title of the notification, displayed in the notifications center. +- `alertAction`- The "action" displayed beneath an actionable notification on the lockscreen (e.g. "Slide to **open**"). Note that Apple no longer shows this in iOS 10. +- `soundName`- The sound played when the notification is fired (optional -- will play default sound if unspecified). This must be the filename of a sound included in the application bundle; the sound must be 30 seconds or less and should be encoded with linear PCM or IMA4. +- `silent`- Whether the notification sound should be suppressed (optional). +- `category`- The category of this notification, required for [interactive notifications](#interactive--actionable-notifications-ios-only) (optional). +- `userInfo`- An optional object containing additional notification data. + +### Cancel Scheduled Local Notifications + +The `NotificationsIOS.localNotification()` and `NotificationsAndroid.localNotification()` methods return unique `notificationId` values, which can be used in order to cancel specific local notifications that were scheduled for delivery on `fireDate` and have not yet been delivered. You can cancel local notification by calling `NotificationsIOS.cancelLocalNotification(notificationId)` or `NotificationsAndroid.cancelLocalNotification(notificationId)`. + +Example: + +```javascript +let someLocalNotification = NotificationsIOS.localNotification({ + alertBody: "Local notificiation!", + alertTitle: "Local Notification Title", + soundName: "chime.aiff", + category: "SOME_CATEGORY", + userInfo: { } +}); + +NotificationsIOS.cancelLocalNotification(someLocalNotification); +``` + +To cancel all local notifications (**iOS only!**), use `cancelAllLocalNotifications()`: + +```javascript +NotificationsIOS.cancelAllLocalNotifications(); +``` + +#### Cancel Delivered Local Notifications (iOS 10+ only) + +To dismiss notifications from the notification center that have already been shown to the user, call `NotificationsIOS.removeDeliveredNotifications([notificationId])`: + +```javascript +let someLocalNotification = NotificationsIOS.localNotification({...}); + +NotificationsIOS.removeDeliveredNotifications([someLocalNotification]); +``` + +Call `removeAllDeliveredNotifications()` to dismiss all delivered notifications +(note that this will dismiss push notifications in addition to local +notifications). + + +## Android + +Much like on iOS, notifications can be triggered locally. The API to do so is a simplified version of the iOS equivalent that works more natually with the Android perception of push (remote) notifications: + +```javascript +NotificationsAndroid.localNotification({ + title: "Local notification", + body: "This notification was generated by the app!", + extra: "data" +}); +``` + +Upon notification opening (tapping by the device user), all data fields will be delivered as-is). diff --git a/docs/notificationsEvents.md b/docs/notificationsEvents.md new file mode 100644 index 000000000..1a1c0b975 --- /dev/null +++ b/docs/notificationsEvents.md @@ -0,0 +1,113 @@ + +# Handling Notification Events + +## iOS + +When a push notification is received by the device, the application can be in one of the following states: + +1. **Forground:** When the app is running and is used by the user right now; in this case, a `notificationReceivedForeground` event will be fired. +2. **Background:** When the app is running in a background state; in this case, a `notificationReceivedBackground` event will be fired. + +Finally, when a notification is _opened_ by the device user (i.e. tapped-on), a `notificationOpened` event is fired. + +Example: + +```javascript +constructor() { + this._boundOnNotificationReceivedForeground = this.onNotificationReceivedForeground.bind(this); + this._boundOnNotificationReceivedBackground = this.onNotificationReceivedBackground.bind(this); + this._boundOnNotificationOpened = this.onNotificationOpened.bind(this); + + NotificationsIOS.addEventListener('notificationReceivedForeground', this._boundOnNotificationReceivedForeground); + NotificationsIOS.addEventListener('notificationReceivedBackground', this._boundOnNotificationReceivedBackground); + NotificationsIOS.addEventListener('notificationOpened', this._boundOnNotificationOpened); +} + +onNotificationReceivedForeground(notification) { + console.log("Notification Received - Foreground", notification); +} + +onNotificationReceivedBackground(notification) { + console.log("Notification Received - Background", notification); +} + +onNotificationOpened(notification) { + console.log("Notification opened by device user", notification); +} + +componentWillUnmount() { + // Don't forget to remove the event listeners to prevent memory leaks! + NotificationsIOS.removeEventListener('notificationReceivedForeground', this._boundOnNotificationReceivedForeground); + NotificationsIOS.removeEventListener('notificationReceivedBackground', this._boundOnNotificationReceivedBackground); + NotificationsIOS.removeEventListener('notificationOpened', this._boundOnNotificationOpened); +} +``` + +### Notification Object + +When you receive a push notification, you'll get an instance of `IOSNotification` object, contains the following methods: + +- **`getMessage()`**- returns the notification's main message string. +- **`getSound()`**- returns the sound string from the `aps` object. +- **`getBadgeCount()`**- returns the badge count number from the `aps` object. +- **`getCategory()`**- returns the category from the `aps` object (related to interactive notifications). +- **`getData()`**- returns the data payload (additional info) of the notification. +- **`getType()`**- returns `managed` for managed notifications, otherwise returns `regular`. + +### Background Queue (Important - please read!) + +When a push notification is opened but the app is not running, the application will be in a **cold launch** state, until the JS engine is up and ready to handle the notification. +The application will collect the events (notifications, actions, etc.) that happend during the cold launch for you. + +When your app is ready (most of the time it's after the call to `requestPermissions()`), just call to `NotificationsIOS.consumeBackgroundQueue();` in order to consume the background queue. For more info see `index.ios.js` in the example app. + +## Android + +On Android the same core functionality is provided, but using a different API: + +```javascript +import {NotificationsAndroid} from 'react-native-notifications'; + +// On Android, we allow for only one (global) listener per each event type. +NotificationsAndroid.setNotificationReceivedListener((notification) => { + console.log("Notification received on device in background or foreground", notification.getData()); +}); +NotificationsAndroid.setNotificationReceivedInForegroundListener((notification) => { + console.log("Notification received on device in foreground", notification.getData()); +}); +NotificationsAndroid.setNotificationOpenedListener((notification) => { + console.log("Notification opened by device user", notification.getData()); +}); +``` + +### Notification Object + +- **`getData()`**- content of the `data` section of the original message (sent to GCM). +- **`getTitle()`**- Convenience for returning `data.title`. +- **`getMessage()`**- Convenience for returning `data.body`. + + + +## Querying initial notification (Android) + +React-Native's [`PushNotificationsIOS.getInitialNotification()`](https://facebook.github.io/react-native/docs/pushnotificationios.html#getinitialnotification) allows for the async retrieval of the original notification used to open the App on iOS, but it has no equivalent implementation for Android. + +While for iOS we nonetheless offer the more elaborate _Background Queue_ solution, on Android we've settled for an implementation similar to React Native's -- An API method `PendingNotifications.getInitialNotification()`, which returns a promise: + +```javascript +import {NotificationsAndroid, PendingNotifications} from 'react-native-notifications'; + +PendingNotifications.getInitialNotification() + .then((notification) => { + console.log("Initial notification was:", (notification ? notification.getData() : 'N/A')); + }) + .catch((err) => console.error("getInitialNotifiation() failed", err)); + +``` + +> **Note** +> +> Notifications are considered 'initial' under the following terms: + +> - User tapped on a notification, _AND_ - +> - App was either not running at all ("dead" state), _OR_ it existed in the background with **no running activities** associated with it. diff --git a/docs/subscription.md b/docs/subscription.md new file mode 100644 index 000000000..ddd493e62 --- /dev/null +++ b/docs/subscription.md @@ -0,0 +1,77 @@ +# Push Notifications Subscription + +The typical flow for subscribing a device for receiving push notification in real time is to first register the device at the vendor's servers (e.g. GCM), then publishing the received token to your own push management servers. + +This section is about the first part of the flow. + +## iOS + +In order to handle notifications, you must register the `remoteNotificationsRegistered` event beforehand. + + +In your React Native app: + +```javascript +import NotificationsIOS from 'react-native-notifications'; + +class App extends Component { + constructor() { + NotificationsIOS.addEventListener('remoteNotificationsRegistered', this.onPushRegistered.bind(this)); + NotificationsIOS.addEventListener('remoteNotificationsRegistrationFailed', this.onPushRegistrationFailed.bind(this)); + NotificationsIOS.requestPermissions(); + } + + onPushRegistered(deviceToken) { + // TODO: Send the token to my server so it could send back push notifications... + console.log("Device Token Received", deviceToken); + } + + onPushRegistrationFailed(error) { + // For example: + // + // error={ + // domain: 'NSCocoaErroDomain', + // code: 3010, + // localizedDescription: 'remote notifications are not supported in the simulator' + // } + console.error(error); + } + + componentWillUnmount() { + // prevent memory leaks! + NotificationsIOS.removeEventListener('remoteNotificationsRegistered', this.onPushRegistered.bind(this)); + NotificationsIOS.removeEventListener('remoteNotificationsRegistrationFailed', this.onPushRegistrationFailed.bind(this)); + } +} + +``` + +When you have the device token, POST it to your server and register the device in your notifications provider (Amazon SNS, Azure, etc.). + +You can check if the user granted permissions by calling `checkPermissions()`: + +```javascript +NotificationsIOS.checkPermissions().then((currentPermissions) => { + console.log('Badges enabled: ' + !!currentPermissions.badge); + console.log('Sounds enabled: ' + !!currentPermissions.sound); + console.log('Alerts enabled: ' + !!currentPermissions.alert); +}); +``` + + +## Android + +Android works similarly but using a different API; The equivalent code is: + +```javascript +import {NotificationsAndroid} from 'react-native-notifications'; + +// On Android, we allow for only one (global) listener per each event type. +NotificationsAndroid.setRegistrationTokenUpdateListener((deviceToken) => { + // TODO: Send the token to my server so it could send back push notifications... + console.log('Push-notifications registered!', deviceToken) +}); + +``` + +`deviceToken` being the token used to identify the device on the GCM. diff --git a/example/.flowconfig b/example/.flowconfig index f565799e7..1043c82d7 100644 --- a/example/.flowconfig +++ b/example/.flowconfig @@ -1,58 +1,70 @@ [ignore] - -# We fork some components by platform. +; We fork some components by platform .*/*[.]android.js -# Ignore templates with `@flow` in header -.*/local-cli/generator.* - -# Ignore malformed json -.*/node_modules/y18n/test/.*\.json - -# Ignore the website subdir -/website/.* - -# Ignore BUCK generated dirs +; Ignore "BUCK" generated dirs /\.buckd/ -# Ignore unexpected extra @providesModule -.*/node_modules/commoner/test/source/widget/share.js +; Ignore unexpected extra "@providesModule" +.*/node_modules/.*/node_modules/fbjs/.* -# Ignore duplicate module providers -# For RN Apps installed via npm, "Libraries" folder is inside node_modules/react-native but in the source repo it is in the root +; Ignore duplicate module providers +; For RN Apps installed via npm, "Libraries" folder is inside +; "node_modules/react-native" but in the source repo it is in the root .*/Libraries/react-native/React.js -.*/Libraries/react-native/ReactNative.js -.*/node_modules/jest-runtime/build/__tests__/.* + +; Ignore polyfills +.*/Libraries/polyfills/.* + +; Ignore metro +.*/node_modules/metro/.* [include] [libs] node_modules/react-native/Libraries/react-native/react-native-interface.js -node_modules/react-native/flow -flow/ +node_modules/react-native/flow/ +node_modules/react-native/flow-github/ [options] -module.system=haste +emoji=true -esproposal.class_static_fields=enable -esproposal.class_instance_fields=enable +esproposal.optional_chaining=enable +esproposal.nullish_coalescing=enable -experimental.strict_type_args=true +module.system=haste +module.system.haste.use_name_reducers=true +# get basename +module.system.haste.name_reducers='^.*/\([a-zA-Z0-9$_.-]+\.js\(\.flow\)?\)$' -> '\1' +# strip .js or .js.flow suffix +module.system.haste.name_reducers='^\(.*\)\.js\(\.flow\)?$' -> '\1' +# strip .ios suffix +module.system.haste.name_reducers='^\(.*\)\.ios$' -> '\1' +module.system.haste.name_reducers='^\(.*\)\.android$' -> '\1' +module.system.haste.name_reducers='^\(.*\)\.native$' -> '\1' +module.system.haste.paths.blacklist=.*/__tests__/.* +module.system.haste.paths.blacklist=.*/__mocks__/.* +module.system.haste.paths.blacklist=/node_modules/react-native/Libraries/Animated/src/polyfills/.* +module.system.haste.paths.whitelist=/node_modules/react-native/Libraries/.* munge_underscores=true -module.name_mapper='^image![a-zA-Z0-9$_-]+$' -> 'GlobalImageStub' module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub' +module.file_ext=.js +module.file_ext=.jsx +module.file_ext=.json +module.file_ext=.native.js + suppress_type=$FlowIssue suppress_type=$FlowFixMe -suppress_type=$FixMe +suppress_type=$FlowFixMeProps +suppress_type=$FlowFixMeState -suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(3[0-2]\\|[1-2][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\) -suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(3[0-2]\\|1[0-9]\\|[1-2][0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+ +suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\) +suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+ suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy - -unsafe.enable_getters_and_setters=true +suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError [version] -^0.32.0 +^0.78.0 diff --git a/example/.gitignore b/example/.gitignore index eb1535e41..5d647565f 100644 --- a/example/.gitignore +++ b/example/.gitignore @@ -22,20 +22,35 @@ DerivedData *.xcuserstate project.xcworkspace -# Android/IJ +# Android/IntelliJ # -*.iml +build/ .idea .gradle local.properties +*.iml # node.js # node_modules/ npm-debug.log +yarn-error.log # BUCK buck-out/ \.buckd/ -android/app/libs -android/keystores/debug.keystore +*.keystore + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/ + +*/fastlane/report.xml +*/fastlane/Preview.html +*/fastlane/screenshots + +# Bundle artifact +*.jsbundle diff --git a/example/android/build.gradle b/example/android/build.gradle index f2464c16c..f5195f5cf 100644 --- a/example/android/build.gradle +++ b/example/android/build.gradle @@ -2,15 +2,21 @@ buildscript { repositories { + google() + mavenLocal() + mavenCentral() jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.2.0' + classpath 'com.android.tools.build:gradle:3.2.1' } } allprojects { repositories { + mavenLocal() + mavenCentral() + google() jcenter() maven { diff --git a/example/android/gradle/wrapper/gradle-wrapper.properties b/example/android/gradle/wrapper/gradle-wrapper.properties index 1d4f8cb26..77c772103 100644 --- a/example/android/gradle/wrapper/gradle-wrapper.properties +++ b/example/android/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Sun Oct 09 14:30:04 IDT 2016 +#Sun Nov 04 14:31:28 IST 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip diff --git a/example/android/myapplication/build.gradle b/example/android/myapplication/build.gradle index 25b480757..f5fb4798e 100644 --- a/example/android/myapplication/build.gradle +++ b/example/android/myapplication/build.gradle @@ -1,22 +1,19 @@ apply plugin: 'com.android.application' android { - compileSdkVersion 23 - buildToolsVersion "25" + compileSdkVersion 26 + buildToolsVersion "28.0.3" defaultConfig { applicationId "com.wix.reactnativenotifications.app" minSdkVersion 16 - targetSdkVersion 23 + targetSdkVersion 26 versionCode 1 versionName "1.0" ndk { abiFilters "armeabi-v7a", "x86" } -// packagingOptions { -// exclude "lib/arm64-v8a/librealm-jni.so" -// } } buildTypes { release { @@ -26,13 +23,24 @@ android { } } +configurations.all { + resolutionStrategy.eachDependency { DependencyResolveDetails details -> + def requested = details.requested + if (requested.group == 'com.android.support') { + if (!requested.name.startsWith("multidex")) { + details.useVersion "26.1.0" + } + } + } +} + dependencies { - compile fileTree(dir: 'libs', include: ['*.jar']) +// compile fileTree(dir: 'libs', include: ['*.jar']) - compile 'com.android.support:appcompat-v7:23.4.0' - compile 'com.android.support:design:23.4.0' - compile 'com.facebook.react:react-native:+' - compile project(':react-native-notifications') + implementation 'com.android.support:appcompat-v7:26.1.0' + implementation 'com.android.support:design:26.1.0' + implementation 'com.facebook.react:react-native:+' + implementation project(':react-native-notifications') - testCompile 'junit:junit:4.12' + testImplementation'junit:junit:4.12' } diff --git a/example/android/myapplication/src/main/java/com/wix/reactnativenotifications/app/MainActivity.java b/example/android/myapplication/src/main/java/com/wix/reactnativenotifications/app/MainActivity.java index 35edad8bc..4459a6a3e 100644 --- a/example/android/myapplication/src/main/java/com/wix/reactnativenotifications/app/MainActivity.java +++ b/example/android/myapplication/src/main/java/com/wix/reactnativenotifications/app/MainActivity.java @@ -1,11 +1,7 @@ package com.wix.reactnativenotifications.app; -import android.annotation.TargetApi; -import android.content.Intent; -import android.net.Uri; import android.os.Build; import android.os.Bundle; -import android.provider.Settings; import android.view.ViewGroup; import android.widget.Toolbar; @@ -16,42 +12,26 @@ public class MainActivity extends ReactActivity { - private static final int OVERLAY_PERMISSION_REQ_CODE = 1234; - private ReactRootView mReactRootView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - final ViewGroup layout = (ViewGroup) getLayoutInflater().inflate(R.layout.activity_main, null); + ViewGroup layout; if (SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - Toolbar toolbar = (Toolbar) layout.findViewById(R.id.toolbar); + layout = (ViewGroup) getLayoutInflater().inflate(R.layout.activity_main, null); + Toolbar toolbar = layout.findViewById(R.id.toolbar); setActionBar(toolbar); + } else { + layout = (ViewGroup) getLayoutInflater().inflate(R.layout.activity_main_prelollipop, null); } mReactRootView = new ReactRootView(this); layout.addView(mReactRootView); setContentView(layout); - if (SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) { - Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); - startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE); - } else { - startReactApplication(); - } - } - - @TargetApi(Build.VERSION_CODES.M) - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - if (requestCode == OVERLAY_PERMISSION_REQ_CODE) { - if (Settings.canDrawOverlays(this)) { - startReactApplication(); - } else { - finish(); - } - } + startReactApplication(); } private void startReactApplication() { diff --git a/example/android/myapplication/src/main/java/com/wix/reactnativenotifications/app/MainApplication.java b/example/android/myapplication/src/main/java/com/wix/reactnativenotifications/app/MainApplication.java index 350b838f8..87b0d3a6e 100644 --- a/example/android/myapplication/src/main/java/com/wix/reactnativenotifications/app/MainApplication.java +++ b/example/android/myapplication/src/main/java/com/wix/reactnativenotifications/app/MainApplication.java @@ -15,7 +15,7 @@ public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override - protected boolean getUseDeveloperSupport() { + public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } diff --git a/example/android/myapplication/src/main/res/layout/activity_main.xml b/example/android/myapplication/src/main/res/layout/activity_main.xml index 349ccb5bb..3f5177974 100644 --- a/example/android/myapplication/src/main/res/layout/activity_main.xml +++ b/example/android/myapplication/src/main/res/layout/activity_main.xml @@ -11,7 +11,8 @@ + android:theme="@style/AppTheme.AppBarOverlay" + > + + + diff --git a/example/android/send_notif.py b/example/android/send_notif.py old mode 100644 new mode 100755 index 969c79fbb..7ac4211bf --- a/example/android/send_notif.py +++ b/example/android/send_notif.py @@ -1,3 +1,4 @@ +#!/usr/bin/python from urllib2 import * import json import sys diff --git a/example/index.android.js b/example/index.android.js index 24274b15a..af61676b8 100644 --- a/example/index.android.js +++ b/example/index.android.js @@ -32,7 +32,7 @@ function onNotificationReceived(notification) { } // It's highly recommended to keep listeners registration at global scope rather than at screen-scope seeing that -// component mount and unmount lifecycle tend to be asymmetric! +// component mount and unmount lifecycle tends to be asymmetric! NotificationsAndroid.setRegistrationTokenUpdateListener(onPushRegistered); NotificationsAndroid.setNotificationOpenedListener(onNotificationOpened); NotificationsAndroid.setNotificationReceivedListener(onNotificationReceived); @@ -89,7 +89,7 @@ class MainComponent extends Component { componentDidMount() { console.log('ReactScreen', 'componentDidMount'); PendingNotifications.getInitialNotification() - .then((notification) => {console.log("getInitialNotification:", notification); this.setState({initialNotification: notification.getData()});}) + .then((notification) => {console.log("getInitialNotification:", notification); this.setState({initialNotification: (notification ? notification.getData() : undefined)});}) .catch((err) => console.error("getInitialNotifiation failed", err)); } @@ -126,10 +126,22 @@ class MainComponent extends Component { this.onCancelNotification()}> Undo last + this.onCheckPermissions()}> + Check permissions + ) } + async onCheckPermissions() { + const hasPermissions = await NotificationsAndroid.isRegisteredForRemoteNotifications(); + if (hasPermissions) { + alert('Yay! You have permissions'); + } else { + alert('Boo! You don\'t have permissions'); + } + } + onPushRegistered() { } diff --git a/example/ios/NotificationsExampleApp.xcodeproj/project.pbxproj b/example/ios/NotificationsExampleApp.xcodeproj/project.pbxproj index 4ce032562..8c0a25370 100644 --- a/example/ios/NotificationsExampleApp.xcodeproj/project.pbxproj +++ b/example/ios/NotificationsExampleApp.xcodeproj/project.pbxproj @@ -12,7 +12,6 @@ 00C302E81ABCBA2D00DB3ED1 /* libRCTImage.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302C01ABCB91800DB3ED1 /* libRCTImage.a */; }; 00C302E91ABCBA2D00DB3ED1 /* libRCTNetwork.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */; }; 00C302EA1ABCBA2D00DB3ED1 /* libRCTVibration.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */; }; - 00E356F31AD99517003FC87E /* NotificationsExampleAppTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* NotificationsExampleAppTests.m */; }; 133E29F31AD74F7200F7D852 /* libRCTLinking.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C398B91ACF4ADC00677621 /* libRCTLinking.a */; }; 139105C61AF99C1200B5F7CC /* libRCTSettings.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 139105C11AF99BAD00B5F7CC /* libRCTSettings.a */; }; 139FDEF61B0652A700C62182 /* libRCTWebSocket.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 139FDEF41B06529B00C62182 /* libRCTWebSocket.a */; }; @@ -20,7 +19,6 @@ 13B07FBD1A68108700A75B9A /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB11A68108700A75B9A /* LaunchScreen.xib */; }; 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; }; 13B07FC11A68108700A75B9A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; }; - 140ED2AC1D01E1AD002B40FF /* libReact.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 146834041AC3E56700842450 /* libReact.a */; }; 146834051AC3E58100842450 /* libReact.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 146834041AC3E56700842450 /* libReact.a */; }; 832341BD1AAA6AB300B99B32 /* libRCTText.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 832341B51AAA6A8300B99B32 /* libRCTText.a */; }; D85498D21D97B37F00DEEE06 /* libRNNotifications.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D85498D11D97B31100DEEE06 /* libRNNotifications.a */; }; @@ -62,13 +60,6 @@ remoteGlobalIDString = 832C81801AAF6DEF007FA2F7; remoteInfo = RCTVibration; }; - 00E356F41AD99517003FC87E /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 13B07F861A680F5B00A75B9A; - remoteInfo = NotificationsExampleApp; - }; 139105C01AF99BAD00B5F7CC /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */; @@ -90,6 +81,104 @@ remoteGlobalIDString = 83CBBA2E1A601D0E00E9B192; remoteInfo = React; }; + 18B5569B2007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3DBE0D001F3B181A0099AA32; + remoteInfo = fishhook; + }; + 18B5569D2007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3DBE0D0D1F3B181C0099AA32; + remoteInfo = "fishhook-tvOS"; + }; + 18B556AD2007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D3C059A1DE3340900C268FA; + remoteInfo = yoga; + }; + 18B556AF2007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D3C06751DE3340C00C268FA; + remoteInfo = "yoga-tvOS"; + }; + 18B556B12007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D3CD9251DE5FBEC00167DC4; + remoteInfo = cxxreact; + }; + 18B556B32007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D3CD9321DE5FBEE00167DC4; + remoteInfo = "cxxreact-tvOS"; + }; + 18B556B52007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D3CD90B1DE5FBD600167DC4; + remoteInfo = jschelpers; + }; + 18B556B72007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D3CD9181DE5FBD800167DC4; + remoteInfo = "jschelpers-tvOS"; + }; + 18B556B92007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 139D7ECE1E25DB7D00323FB7; + remoteInfo = "third-party"; + }; + 18B556BB2007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D383D3C1EBD27B6005632C8; + remoteInfo = "third-party-tvOS"; + }; + 18B556BD2007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 139D7E881E25C6D100323FB7; + remoteInfo = "double-conversion"; + }; + 18B556BF2007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D383D621EBD27B9005632C8; + remoteInfo = "double-conversion-tvOS"; + }; + 18B556C12007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 9936F3131F5F2E4B0010BF04; + remoteInfo = privatedata; + }; + 18B556C32007789B007ACD82 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 9936F32F1F5F2E5B0010BF04; + remoteInfo = "privatedata-tvOS"; + }; 18BA9BF01DEC2288001F416D /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */; @@ -169,7 +258,6 @@ 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTImage.xcodeproj; path = "../node_modules/react-native/Libraries/Image/RCTImage.xcodeproj"; sourceTree = ""; }; 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTNetwork.xcodeproj; path = "../node_modules/react-native/Libraries/Network/RCTNetwork.xcodeproj"; sourceTree = ""; }; 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTVibration.xcodeproj; path = "../node_modules/react-native/Libraries/Vibration/RCTVibration.xcodeproj"; sourceTree = ""; }; - 00E356EE1AD99517003FC87E /* NotificationsExampleAppTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = NotificationsExampleAppTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 00E356F11AD99517003FC87E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 00E356F21AD99517003FC87E /* NotificationsExampleAppTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = NotificationsExampleAppTests.m; sourceTree = ""; }; 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTSettings.xcodeproj; path = "../node_modules/react-native/Libraries/Settings/RCTSettings.xcodeproj"; sourceTree = ""; }; @@ -188,14 +276,6 @@ /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - 00E356EB1AD99517003FC87E /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 140ED2AC1D01E1AD002B40FF /* libReact.a in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; 13B07F8C1A680F5B00A75B9A /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -290,6 +370,8 @@ children = ( 139FDEF41B06529B00C62182 /* libRCTWebSocket.a */, 18BA9C061DEC2288001F416D /* libRCTWebSocket-tvOS.a */, + 18B5569C2007789B007ACD82 /* libfishhook.a */, + 18B5569E2007789B007ACD82 /* libfishhook-tvOS.a */, ); name = Products; sourceTree = ""; @@ -312,7 +394,19 @@ isa = PBXGroup; children = ( 146834041AC3E56700842450 /* libReact.a */, - 18BA9C0A1DEC2288001F416D /* libReact-tvOS.a */, + 18BA9C0A1DEC2288001F416D /* libReact.a */, + 18B556AE2007789B007ACD82 /* libyoga.a */, + 18B556B02007789B007ACD82 /* libyoga.a */, + 18B556B22007789B007ACD82 /* libcxxreact.a */, + 18B556B42007789B007ACD82 /* libcxxreact.a */, + 18B556B62007789B007ACD82 /* libjschelpers.a */, + 18B556B82007789B007ACD82 /* libjschelpers.a */, + 18B556BA2007789B007ACD82 /* libthird-party.a */, + 18B556BC2007789B007ACD82 /* libthird-party.a */, + 18B556BE2007789B007ACD82 /* libdouble-conversion.a */, + 18B556C02007789B007ACD82 /* libdouble-conversion.a */, + 18B556C22007789B007ACD82 /* libprivatedata.a */, + 18B556C42007789B007ACD82 /* libprivatedata-tvOS.a */, ); name = Products; sourceTree = ""; @@ -369,7 +463,6 @@ isa = PBXGroup; children = ( 13B07F961A680F5B00A75B9A /* NotificationsExampleApp.app */, - 00E356EE1AD99517003FC87E /* NotificationsExampleAppTests.xctest */, ); name = Products; sourceTree = ""; @@ -385,24 +478,6 @@ /* End PBXGroup section */ /* Begin PBXNativeTarget section */ - 00E356ED1AD99517003FC87E /* NotificationsExampleAppTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "NotificationsExampleAppTests" */; - buildPhases = ( - 00E356EA1AD99517003FC87E /* Sources */, - 00E356EB1AD99517003FC87E /* Frameworks */, - 00E356EC1AD99517003FC87E /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 00E356F51AD99517003FC87E /* PBXTargetDependency */, - ); - name = NotificationsExampleAppTests; - productName = NotificationsExampleAppTests; - productReference = 00E356EE1AD99517003FC87E /* NotificationsExampleAppTests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; 13B07F861A680F5B00A75B9A /* NotificationsExampleApp */ = { isa = PBXNativeTarget; buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "NotificationsExampleApp" */; @@ -429,12 +504,6 @@ attributes = { LastUpgradeCheck = 0810; ORGANIZATIONNAME = Facebook; - TargetAttributes = { - 00E356ED1AD99517003FC87E = { - CreatedOnToolsVersion = 6.2; - TestTargetID = 13B07F861A680F5B00A75B9A; - }; - }; }; buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "NotificationsExampleApp" */; compatibilityVersion = "Xcode 3.2"; @@ -496,7 +565,6 @@ projectRoot = ""; targets = ( 13B07F861A680F5B00A75B9A /* NotificationsExampleApp */, - 00E356ED1AD99517003FC87E /* NotificationsExampleAppTests */, ); }; /* End PBXProject section */ @@ -558,6 +626,104 @@ remoteRef = 146834031AC3E56700842450 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; + 18B5569C2007789B007ACD82 /* libfishhook.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libfishhook.a; + remoteRef = 18B5569B2007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 18B5569E2007789B007ACD82 /* libfishhook-tvOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libfishhook-tvOS.a"; + remoteRef = 18B5569D2007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 18B556AE2007789B007ACD82 /* libyoga.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libyoga.a; + remoteRef = 18B556AD2007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 18B556B02007789B007ACD82 /* libyoga.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libyoga.a; + remoteRef = 18B556AF2007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 18B556B22007789B007ACD82 /* libcxxreact.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libcxxreact.a; + remoteRef = 18B556B12007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 18B556B42007789B007ACD82 /* libcxxreact.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libcxxreact.a; + remoteRef = 18B556B32007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 18B556B62007789B007ACD82 /* libjschelpers.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libjschelpers.a; + remoteRef = 18B556B52007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 18B556B82007789B007ACD82 /* libjschelpers.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libjschelpers.a; + remoteRef = 18B556B72007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 18B556BA2007789B007ACD82 /* libthird-party.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libthird-party.a"; + remoteRef = 18B556B92007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 18B556BC2007789B007ACD82 /* libthird-party.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libthird-party.a"; + remoteRef = 18B556BB2007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 18B556BE2007789B007ACD82 /* libdouble-conversion.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libdouble-conversion.a"; + remoteRef = 18B556BD2007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 18B556C02007789B007ACD82 /* libdouble-conversion.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libdouble-conversion.a"; + remoteRef = 18B556BF2007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 18B556C22007789B007ACD82 /* libprivatedata.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libprivatedata.a; + remoteRef = 18B556C12007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 18B556C42007789B007ACD82 /* libprivatedata-tvOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libprivatedata-tvOS.a"; + remoteRef = 18B556C32007789B007ACD82 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; 18BA9BF11DEC2288001F416D /* libRCTImage-tvOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; @@ -600,10 +766,10 @@ remoteRef = 18BA9C051DEC2288001F416D /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 18BA9C0A1DEC2288001F416D /* libReact-tvOS.a */ = { + 18BA9C0A1DEC2288001F416D /* libReact.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; - path = "libReact-tvOS.a"; + path = libReact.a; remoteRef = 18BA9C091DEC2288001F416D /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -631,13 +797,6 @@ /* End PBXReferenceProxy section */ /* Begin PBXResourcesBuildPhase section */ - 00E356EC1AD99517003FC87E /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; 13B07F8E1A680F5B00A75B9A /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; @@ -662,19 +821,11 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "export NODE_BINARY=node\n../node_modules/react-native/packager/react-native-xcode.sh"; + shellScript = "export NODE_BINARY=node\n../node_modules/react-native/scripts/react-native-xcode.sh"; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ - 00E356EA1AD99517003FC87E /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 00E356F31AD99517003FC87E /* NotificationsExampleAppTests.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; 13B07F871A680F5B00A75B9A /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -686,14 +837,6 @@ }; /* End PBXSourcesBuildPhase section */ -/* Begin PBXTargetDependency section */ - 00E356F51AD99517003FC87E /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 13B07F861A680F5B00A75B9A /* NotificationsExampleApp */; - targetProxy = 00E356F41AD99517003FC87E /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - /* Begin PBXVariantGroup section */ 13B07FB11A68108700A75B9A /* LaunchScreen.xib */ = { isa = PBXVariantGroup; @@ -707,37 +850,6 @@ /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ - 00E356F61AD99517003FC87E /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - INFOPLIST_FILE = NotificationsExampleAppTests/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)"; - PRODUCT_NAME = "$(TARGET_NAME)"; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/NotificationsExampleApp.app/NotificationsExampleApp"; - }; - name = Debug; - }; - 00E356F71AD99517003FC87E /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - COPY_PHASE_STRIP = NO; - INFOPLIST_FILE = NotificationsExampleAppTests/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)"; - PRODUCT_NAME = "$(TARGET_NAME)"; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/NotificationsExampleApp.app/NotificationsExampleApp"; - }; - name = Release; - }; 13B07F941A680F5B00A75B9A /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -748,9 +860,10 @@ "$(inherited)", /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "$(SRCROOT)/../node_modules/react-native/React/**", - "$(SRCROOT)/../node_modules/react-native-notifications/**", + "$(SRCROOT)/../node_modules/react-native-notifications/RNNotifications/**", ); INFOPLIST_FILE = NotificationsExampleApp/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; OTHER_LDFLAGS = ( "$(inherited)", @@ -772,9 +885,10 @@ "$(inherited)", /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "$(SRCROOT)/../node_modules/react-native/React/**", - "$(SRCROOT)/../node_modules/react-native-notifications/**", + "$(SRCROOT)/../node_modules/react-native-notifications/RNNotifications/**", ); INFOPLIST_FILE = NotificationsExampleApp/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; OTHER_LDFLAGS = ( "$(inherited)", @@ -830,7 +944,7 @@ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "$(SRCROOT)/../node_modules/react-native/React/**", ); - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -873,7 +987,7 @@ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "$(SRCROOT)/../node_modules/react-native/React/**", ); - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; VALIDATE_PRODUCT = YES; @@ -883,15 +997,6 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "NotificationsExampleAppTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 00E356F61AD99517003FC87E /* Debug */, - 00E356F71AD99517003FC87E /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "NotificationsExampleApp" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/example/ios/NotificationsExampleApp.xcodeproj/xcshareddata/xcschemes/NotificationsExampleApp.xcscheme b/example/ios/NotificationsExampleApp.xcodeproj/xcshareddata/xcschemes/NotificationsExampleApp.xcscheme index 3bf6f37c1..a2024ecd9 100644 --- a/example/ios/NotificationsExampleApp.xcodeproj/xcshareddata/xcschemes/NotificationsExampleApp.xcscheme +++ b/example/ios/NotificationsExampleApp.xcodeproj/xcshareddata/xcschemes/NotificationsExampleApp.xcscheme @@ -3,7 +3,7 @@ LastUpgradeVersion = "0810" version = "1.3"> + BlueprintIdentifier = "83CBBA2D1A601D0E00E9B192" + BuildableName = "libReact.a" + BlueprintName = "React" + ReferencedContainer = "container:../node_modules/react-native/React/React.xcodeproj"> @@ -40,18 +40,9 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + language = "" shouldUseLaunchSchemeArgsEnv = "YES"> - - - - + BlueprintIdentifier = "83CBBA2D1A601D0E00E9B192" + BuildableName = "libReact.a" + BlueprintName = "React" + ReferencedContainer = "container:../node_modules/react-native/React/React.xcodeproj"> @@ -40,18 +40,9 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + language = "" shouldUseLaunchSchemeArgsEnv = "YES"> - - - - listener(new NotificationAndroid(notification))); } + static setNotificationReceivedInForegroundListener(listener) { + notificationReceivedInForegroundListener = DeviceEventEmitter.addListener("notificationReceivedInForeground", (notification) => listener(new NotificationAndroid(notification))); + } + static clearNotificationReceivedListener() { if (notificationReceivedListener) { notificationReceivedListener.remove(); @@ -30,6 +35,13 @@ export class NotificationsAndroid { } } + static clearNotificationReceivedInForegroundListener() { + if (notificationReceivedInForegroundListener) { + notificationReceivedInForegroundListener.remove(); + notificationReceivedInForegroundListener = null; + } + } + static setRegistrationTokenUpdateListener(listener) { registrationTokenUpdateListener = DeviceEventEmitter.addListener("remoteNotificationsRegistered", listener); } @@ -41,6 +53,10 @@ export class NotificationsAndroid { } } + static async isRegisteredForRemoteNotifications() { + return await RNNotifications.isRegisteredForRemoteNotifications(); + } + static refreshToken() { RNNotifications.refreshToken(); } @@ -64,7 +80,7 @@ export class PendingNotifications { static getInitialNotification() { return RNNotifications.getInitialNotification() .then((rawNotification) => { - return new NotificationAndroid(rawNotification); + return rawNotification ? new NotificationAndroid(rawNotification) : undefined; }); } } diff --git a/index.ios.js b/index.ios.js index 63f41dc2a..a1c7a54a0 100644 --- a/index.ios.js +++ b/index.ios.js @@ -1,5 +1,4 @@ /** - * @providesModule RNNotifications * @flow */ "use strict"; @@ -10,6 +9,7 @@ const NativeRNNotifications = NativeModules.RNNotifications; // eslint-disable-l import IOSNotification from "./notification.ios"; export const DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT = "remoteNotificationsRegistered"; +export const DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT = "remoteNotificationsRegistrationFailed"; export const DEVICE_PUSH_KIT_REGISTERED_EVENT = "pushKitRegistered"; export const DEVICE_NOTIFICATION_RECEIVED_FOREGROUND_EVENT = "notificationReceivedForeground"; export const DEVICE_NOTIFICATION_RECEIVED_BACKGROUND_EVENT = "notificationReceivedBackground"; @@ -19,6 +19,7 @@ const DEVICE_NOTIFICATION_ACTION_RECEIVED = "notificationActionReceived"; const _exportedEvents = [ DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT, + DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT, DEVICE_PUSH_KIT_REGISTERED_EVENT, DEVICE_NOTIFICATION_RECEIVED_FOREGROUND_EVENT, DEVICE_NOTIFICATION_RECEIVED_BACKGROUND_EVENT, @@ -29,6 +30,9 @@ const _actionHandlers = new Map(); let _actionListener; export class NotificationAction { + options: Object; + handler: Function; + constructor(options: Object, handler: Function) { this.options = options; this.handler = handler; @@ -36,6 +40,8 @@ export class NotificationAction { } export class NotificationCategory { + options: Object; + constructor(options: Object) { this.options = options; } @@ -69,6 +75,11 @@ export default class NotificationsIOS { DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT, registration => handler(registration.deviceToken) ); + } else if (type === DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT) { + listener = DeviceEventEmitter.addListener( + DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT, + error => handler(error) + ); } else if (type === DEVICE_PUSH_KIT_REGISTERED_EVENT) { listener = DeviceEventEmitter.addListener( DEVICE_PUSH_KIT_REGISTERED_EVENT, @@ -156,6 +167,14 @@ export default class NotificationsIOS { _actionHandlers.clear(); } + static getBadgesCount(callback: Function) { + NativeRNNotifications.getBadgesCount(callback); + } + + static setBadgesCount(count: number) { + NativeRNNotifications.setBadgesCount(count); + } + static registerPushKit() { NativeRNNotifications.registerPushKit(); } @@ -172,6 +191,15 @@ export default class NotificationsIOS { NativeRNNotifications.log(message); } + static async getInitialNotification() { + const notification = await NativeRNNotifications.getInitialNotification(); + if (notification) { + return new IOSNotification(notification); + } else { + return undefined; + } + } + /** * Presenting local notification * @@ -181,6 +209,7 @@ export default class NotificationsIOS { * - `alertTitle` : The message title displayed in the notification. * - `alertAction` : The "action" displayed beneath an actionable notification. Defaults to "view"; * - `soundName` : The sound played when the notification is fired (optional). + * - `silent` : If true, the notification sound will be suppressed (optional). * - `category` : The category of this notification, required for actionable notifications (optional). * - `userInfo` : An optional object containing additional notification data. * - `fireDate` : The date and time when the system should deliver the notification. if not specified, the notification will be dispatched immediately. @@ -207,4 +236,47 @@ export default class NotificationsIOS { static cancelAllLocalNotifications() { NativeRNNotifications.cancelAllLocalNotifications(); } + + static isRegisteredForRemoteNotifications() { + return NativeRNNotifications.isRegisteredForRemoteNotifications(); + } + + static checkPermissions() { + return NativeRNNotifications.checkPermissions(); + } + + /** + * Remove all delivered notifications from Notification Center + */ + static removeAllDeliveredNotifications() { + return NativeRNNotifications.removeAllDeliveredNotifications(); + } + + /** + * Removes the specified notifications from Notification Center + * + * @param identifiers Array of notification identifiers + */ + static removeDeliveredNotifications(identifiers: Array) { + return NativeRNNotifications.removeDeliveredNotifications(identifiers); + } + + /** + * Provides you with a list of the app’s notifications that are still displayed in Notification Center + * + * @param callback Function which receive an array of delivered notifications + * + * A delivered notification is an object containing: + * + * - `identifier` : The identifier of this notification. + * - `alertBody` : The message displayed in the notification alert. + * - `alertTitle` : The message title displayed in the notification. + * - `category` : The category of this notification, if has one. + * - `userInfo` : An optional object containing additional notification data. + * - `thread-id` : The thread identifier of this notification, if has one. + * - `fireDate` : The date and time when the system should deliver the notification. if not specified, the notification will be dispatched immediately. + */ + static getDeliveredNotifications(callback: (notifications: Array) => void) { + return NativeRNNotifications.getDeliveredNotifications(callback); + } } diff --git a/notification.ios.js b/notification.ios.js index 3dca98f03..7b40fe45c 100644 --- a/notification.ios.js +++ b/notification.ios.js @@ -9,6 +9,7 @@ export default class IOSNotification { _badge: number; _category: string; _type: string; // regular / managed + _thread: string; constructor(notification: Object) { this._data = {}; @@ -35,6 +36,7 @@ export default class IOSNotification { this._badge = notification.aps.badge; this._category = notification.managedAps.category; this._type = "managed"; + this._thread = notification.aps["thread-id"]; } else if ( notification.aps && notification.aps.alert) { @@ -54,6 +56,7 @@ export default class IOSNotification { this._badge = notification.aps.badge; this._category = notification.aps.category; this._type = "regular"; + this._thread = notification.aps["thread-id"]; } this._id = notification.__id; @@ -96,4 +99,8 @@ export default class IOSNotification { getType(): ?string { return this._type; } + + getThread(): ?string { + return this._thread; + } } diff --git a/package.json b/package.json index b376c5faf..afea6384e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "react-native-notifications", - "version": "1.1.5", + "version": "1.2.0-convoyv9", "description": "Advanced Push Notifications (Silent, interactive notifications) for iOS & Android", "author": "Lidan Hifi ", "license": "MIT", @@ -25,16 +25,16 @@ "uuid": "^2.0.3" }, "peerDependencies": { - "react-native": ">=0.25.1", - "react": ">=0.14.5" + "react": ">=0.14.5", + "react-native": ">=0.25.1" }, "devDependencies": { - "babel-eslint": "^6.0.2", + "babel-eslint": "9.0.0", "babel-preset-react-native": "^1.9.0", "babel-register": "^6.7.2", "chai": "^3.5.0", "chokidar-cli": "^1.2.0", - "eslint": "^2.12.0", + "eslint": "5.1.x", "mocha": "^2.5.3", "proxyquire": "^1.7.4", "sinon": "^1.17.3", diff --git a/test/index.android.spec.js b/test/index.android.spec.js index d47173755..a41255b81 100644 --- a/test/index.android.spec.js +++ b/test/index.android.spec.js @@ -181,13 +181,13 @@ describe("Notifications-Android > ", () => { .catch((err) => done(err)); }); - it("should return empty notification data if not available", (done) => { + it("should return empty notification if not available", (done) => { expect(getInitialNotificationStub).to.not.have.been.called; getInitialNotificationStub.returns(Promise.resolve(null)); libUnderTest.PendingNotifications.getInitialNotification() .then((notification) => { - expect(notification.getData()).to.equal(null); + expect(notification).to.be.undefined; done(); }) .catch((err) => done(err)); diff --git a/test/index.ios.spec.js b/test/index.ios.spec.js index c9cdd8206..295a3b672 100644 --- a/test/index.ios.spec.js +++ b/test/index.ios.spec.js @@ -9,6 +9,7 @@ describe("NotificationsIOS", () => { let deviceEvents = [ "pushKitRegistered", "remoteNotificationsRegistered", + "remoteNotificationsRegistrationFailed", "notificationReceivedForeground", "notificationReceivedBackground", "notificationOpened" @@ -16,20 +17,29 @@ describe("NotificationsIOS", () => { /*eslint-disable indent*/ let deviceAddEventListener, - deviceRemoveEventListener, - nativeAppAddEventListener, - nativeAppRemoveEventListener, - nativeRequestPermissionsWithCategories, - nativeAbandonPermissions, - nativeRegisterPushKit, - nativeBackgroundTimeRemaining, - nativeConsumeBackgroundQueue, - nativeLocalNotification, - nativeCancelLocalNotification, - nativeCancelAllLocalNotifications; + deviceRemoveEventListener, + nativeAppAddEventListener, + nativeAppRemoveEventListener, + nativeRequestPermissionsWithCategories, + nativeAbandonPermissions, + nativeRegisterPushKit, + nativeBackgroundTimeRemaining, + nativeConsumeBackgroundQueue, + nativeLocalNotification, + nativeCancelLocalNotification, + nativeCancelAllLocalNotifications, + nativeGetBadgesCount, + nativeSetBadgesCount, + nativeIsRegisteredForRemoteNotifications, + nativeCheckPermissions, + nativeRemoveAllDeliveredNotifications, + nativeRemoveDeliveredNotifications, + nativeGetDeliveredNotifications; + let NotificationsIOS, NotificationAction, NotificationCategory; let someHandler = () => {}; let constantGuid = "some-random-uuid"; + let identifiers = ["some-random-uuid", "other-random-uuid"]; /*eslint-enable indent*/ before(() => { @@ -45,6 +55,13 @@ describe("NotificationsIOS", () => { nativeLocalNotification = sinon.spy(); nativeCancelLocalNotification = sinon.spy(); nativeCancelAllLocalNotifications = sinon.spy(); + nativeGetBadgesCount = sinon.spy(); + nativeSetBadgesCount = sinon.spy(); + nativeIsRegisteredForRemoteNotifications = sinon.spy(); + nativeCheckPermissions = sinon.spy(); + nativeRemoveAllDeliveredNotifications = sinon.spy(); + nativeRemoveDeliveredNotifications = sinon.spy(); + nativeGetDeliveredNotifications = sinon.spy(); let libUnderTest = proxyquire("../index.ios", { "uuid": { @@ -60,7 +77,14 @@ describe("NotificationsIOS", () => { consumeBackgroundQueue: nativeConsumeBackgroundQueue, localNotification: nativeLocalNotification, cancelLocalNotification: nativeCancelLocalNotification, - cancelAllLocalNotifications: nativeCancelAllLocalNotifications + cancelAllLocalNotifications: nativeCancelAllLocalNotifications, + getBadgesCount: nativeGetBadgesCount, + setBadgesCount: nativeSetBadgesCount, + isRegisteredForRemoteNotifications: nativeIsRegisteredForRemoteNotifications, + checkPermissions: nativeCheckPermissions, + removeAllDeliveredNotifications: nativeRemoveAllDeliveredNotifications, + removeDeliveredNotifications: nativeRemoveDeliveredNotifications, + getDeliveredNotifications: nativeGetDeliveredNotifications } }, NativeAppEventEmitter: { @@ -99,6 +123,11 @@ describe("NotificationsIOS", () => { nativeLocalNotification.reset(); nativeCancelLocalNotification.reset(); nativeCancelAllLocalNotifications.reset(); + nativeIsRegisteredForRemoteNotifications.reset(); + nativeCheckPermissions.reset(); + nativeRemoveAllDeliveredNotifications.reset(); + nativeRemoveDeliveredNotifications.reset(); + nativeGetDeliveredNotifications.reset(); }); after(() => { @@ -114,6 +143,11 @@ describe("NotificationsIOS", () => { nativeLocalNotification = null; nativeCancelLocalNotification = null; nativeCancelAllLocalNotifications = null; + nativeIsRegisteredForRemoteNotifications = null; + nativeCheckPermissions = null; + nativeRemoveAllDeliveredNotifications = null; + nativeRemoveDeliveredNotifications = null; + nativeGetDeliveredNotifications = null; NotificationsIOS = null; NotificationAction = null; @@ -207,6 +241,24 @@ describe("NotificationsIOS", () => { expect(nativeAppRemoveEventListener).to.have.been.calledOnce; }); }); + + describe("get badges count", () => { + it("should call native getBadgesCount", () => { + const callback = (count) => console.log(count); + NotificationsIOS.getBadgesCount(callback); + + expect(nativeGetBadgesCount).to.have.been.calledWith(callback); + }); + }); + + describe("set badges count", () => { + it("should call native setBadgesCount", () => { + NotificationsIOS.setBadgesCount(44); + + expect(nativeSetBadgesCount).to.have.been.calledWith(44); + }); + }); + }); describe("register push kit for background notifications", function () { @@ -281,4 +333,45 @@ describe("NotificationsIOS", () => { expect(nativeCancelAllLocalNotifications).to.have.been.calledWith(); }); }); + + describe("Is registered for remote notifications ", () => { + it("should call native is registered for remote notifications", () => { + NotificationsIOS.isRegisteredForRemoteNotifications(); + expect(nativeIsRegisteredForRemoteNotifications).to.have.been.calledWith(); + + }); + }); + + describe("Check permissions ", () => { + it("should call native check permissions", () => { + NotificationsIOS.checkPermissions(); + expect(nativeCheckPermissions).to.have.been.calledWith(); + + }); + }); + + describe("Remove all delivered notifications", () => { + it("should call native remove all delivered notifications method", () => { + NotificationsIOS.removeAllDeliveredNotifications(); + + expect(nativeRemoveAllDeliveredNotifications).to.have.been.calledWith(); + }); + }); + + describe("Remove delivered notifications", () => { + it("should call native remove delivered notifications method", () => { + NotificationsIOS.removeDeliveredNotifications(identifiers); + + expect(nativeRemoveDeliveredNotifications).to.have.been.calledWith(identifiers); + }); + }); + + describe("Get delivered notifications", () => { + it("should call native get delivered notifications method", () => { + const callback = (notifications) => console.log(notifications); + NotificationsIOS.getDeliveredNotifications(callback); + + expect(nativeGetDeliveredNotifications).to.have.been.calledWith(callback); + }); + }); }); diff --git a/test/notification.ios.spec.js b/test/notification.ios.spec.js index 0620108aa..b19a901f9 100644 --- a/test/notification.ios.spec.js +++ b/test/notification.ios.spec.js @@ -4,7 +4,7 @@ import IOSNotification from "../notification.ios"; describe("iOS Notification Object", () => { let notification; - let someBadgeCount = 123, someSound = "someSound", someCategory = "some_notification_category"; + let someBadgeCount = 123, someSound = "someSound", someCategory = "some_notification_category", someThread = "thread-1"; describe("for a regular iOS push notification", () => { let regularNativeNotifications = [ @@ -17,7 +17,8 @@ describe("iOS Notification Object", () => { }, badge: someBadgeCount, sound: someSound, - category: someCategory + category: someCategory, + "thread-id": someThread }, key1: "value1", key2: "value2" @@ -33,7 +34,8 @@ describe("iOS Notification Object", () => { }, badge: someBadgeCount, sound: someSound, - category: someCategory + category: someCategory, + "thread-id": someThread }, key1: "value1", key2: "value2" @@ -65,6 +67,10 @@ describe("iOS Notification Object", () => { expect(notification.getCategory()).to.equal(someCategory); }); + it("should return the thread", () => { + expect(notification.getThread()).to.equal("thread-1"); + }); + it("should return the custom data", () => { expect(notification.getData()).to.deep.equal({ key1: "value1", key2: "value2" }); });