From 8ae6275441173883d3af47a3933b772aad43024e Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Tue, 20 Jun 2023 11:19:24 -0700
Subject: [PATCH 01/29] run Prettier for linting test failure
---
.github/ISSUE_TEMPLATE/ask-question.yml | 4 +-
.github/ISSUE_TEMPLATE/bug-report.yml | 4 +-
.github/ISSUE_TEMPLATE/general-feedback.yml | 4 +-
.github/pull_request_template.md | 67 +-
.github/release-drafter.yml | 6 +-
.github/workflows/Zapier.yml | 2 +-
.github/workflows/ci.yml | 8 +-
.github/workflows/release-drafter.yml | 1 -
CONTRIBUTING.md | 17 +-
MIGRATION_GUIDE.md | 299 +++---
README.md | 6 +-
examples/RNOneSignalTS/.watchmanconfig | 2 +-
examples/RNOneSignalTS/app.json | 2 +-
.../AppIcon.appiconset/Contents.json | 46 +-
.../Images.xcassets/Contents.json | 6 +-
examples/RNOneSignalTS/src/App.tsx | 4 +-
examples/RNOneSignalTS/src/Helpers.tsx | 117 ++-
examples/RNOneSignalTS/src/OSButtons.tsx | 954 +++++++++---------
examples/RNOneSignalTS/src/OSConsole.tsx | 82 +-
examples/RNOneSignalTS/src/OSDemo.tsx | 32 +-
examples/RNOneSignalTS/tsconfig.json | 30 +-
jest.config.js | 22 +-
src/index.ts | 235 +++--
src/models/InAppMessage.ts | 19 +-
src/models/NotificationEvents.ts | 4 +-
src/models/Subscription.ts | 2 +-
tsconfig.json | 14 +-
27 files changed, 1038 insertions(+), 951 deletions(-)
diff --git a/.github/ISSUE_TEMPLATE/ask-question.yml b/.github/ISSUE_TEMPLATE/ask-question.yml
index dce598c6..f5ad8501 100644
--- a/.github/ISSUE_TEMPLATE/ask-question.yml
+++ b/.github/ISSUE_TEMPLATE/ask-question.yml
@@ -1,7 +1,7 @@
name: 🙋♂️ Ask a question
description: Tell us what's on your mind
-title: "[question]: "
-labels: ["question"]
+title: '[question]: '
+labels: ['question']
# assignees:
# - OneSignal/ios-sdk
body:
diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml
index a80fde12..2c8e9351 100644
--- a/.github/ISSUE_TEMPLATE/bug-report.yml
+++ b/.github/ISSUE_TEMPLATE/bug-report.yml
@@ -1,7 +1,7 @@
name: 🪳 Bug report
description: File a bug report
-title: "[Bug]: "
-labels: ["bug", "triage"]
+title: '[Bug]: '
+labels: ['bug', 'triage']
# assignees:
# - OneSignal/ios-sdk
body:
diff --git a/.github/ISSUE_TEMPLATE/general-feedback.yml b/.github/ISSUE_TEMPLATE/general-feedback.yml
index fbada335..0776fab6 100644
--- a/.github/ISSUE_TEMPLATE/general-feedback.yml
+++ b/.github/ISSUE_TEMPLATE/general-feedback.yml
@@ -1,7 +1,7 @@
name: 📣 General feedback
description: Tell us what's on your mind
-title: "[Feedback]: "
-labels: ["triage"]
+title: '[Feedback]: '
+labels: ['triage']
# assignees:
# - OneSignal/ios-sdk
body:
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 1ce9a81a..ad828eb8 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -1,60 +1,75 @@
+
# READ AND DELETE THIS SECTION BEFORE SUBMITTING PR
-* **Fill out each _REQUIRED_ section**
-* **Fill out _OPTIONAL_ sections, remove section if it doesn't apply to your PR**
-* **Read and fill out each of the checklists below**
-* **Remove this section after reading**
+
+- **Fill out each _REQUIRED_ section**
+- **Fill out _OPTIONAL_ sections, remove section if it doesn't apply to your PR**
+- **Read and fill out each of the checklists below**
+- **Remove this section after reading**
# Description
+
## One Line Summary
+
**REQUIRED** - Very short description that summaries the changes in this PR.
## Details
### Motivation
+
**REQUIRED -** Why is this code change being made? Or what is the goal of this PR? Examples: Fixes a specific bug, provides additional logging to debug future issues, feature to allow X.
### Scope
+
**RECOMMEND - OPTIONAL -** What is intended to be effected. What is known not to change. Example: Notifications are grouped when parameter X is set, not enabled by default.
### OPTIONAL - Other
+
**OPTIONAL -** Feel free to add any other sections or sub-sections that can explain your PR better.
# Testing
+
## Unit testing
-**OPTIONAL -** Explain unit tests added, if not clear in the code.
+
+**OPTIONAL -** Explain unit tests added, if not clear in the code.
## Manual testing
+
**RECOMMEND - OPTIONAL -** Explain what scenarios were tested and the environment.
Example: Tested opening a notification while the app was foregrounded, app build with Android Studio 2020.3 with a fresh install of the OneSignal example app on a Pixel 6 with Android 12.
# Affected code checklist
- - [ ] Notifications
- - [ ] Display
- - [ ] Open
- - [ ] Push Processing
- - [ ] Confirm Deliveries
- - [ ] Outcomes
- - [ ] Sessions
- - [ ] In-App Messaging
- - [ ] REST API requests
- - [ ] Public API changes
+
+- [ ] Notifications
+ - [ ] Display
+ - [ ] Open
+ - [ ] Push Processing
+ - [ ] Confirm Deliveries
+- [ ] Outcomes
+- [ ] Sessions
+- [ ] In-App Messaging
+- [ ] REST API requests
+- [ ] Public API changes
# Checklist
+
## Overview
- - [ ] I have filled out all **REQUIRED** sections above
- - [ ] PR does one thing
- - If it is hard to explain how any codes changes are related to each other then it most likely needs to be more than one PR
- - [ ] Any Public API changes are explained in the PR details and conform to existing APIs
+
+- [ ] I have filled out all **REQUIRED** sections above
+- [ ] PR does one thing
+ - If it is hard to explain how any codes changes are related to each other then it most likely needs to be more than one PR
+- [ ] Any Public API changes are explained in the PR details and conform to existing APIs
## Testing
- - [ ] I have included test coverage for these changes, or explained why they are not needed
- - [ ] All automated tests pass, or I explained why that is not possible
- - [ ] I have personally tested this on my device, or explained why that is not possible
+
+- [ ] I have included test coverage for these changes, or explained why they are not needed
+- [ ] All automated tests pass, or I explained why that is not possible
+- [ ] I have personally tested this on my device, or explained why that is not possible
## Final pass
- - [ ] Code is as readable as possible.
- - Simplify with less code, followed by splitting up code into well named functions and variables, followed by adding comments to the code.
- - [ ] I have reviewed this PR myself, ensuring it meets each checklist item
- - WIP (Work In Progress) is ok, but explain what is still in progress and what you would like feedback on. Start the PR title with "WIP" to indicate this.
\ No newline at end of file
+
+- [ ] Code is as readable as possible.
+ - Simplify with less code, followed by splitting up code into well named functions and variables, followed by adding comments to the code.
+- [ ] I have reviewed this PR myself, ensuring it meets each checklist item
+ - WIP (Work In Progress) is ok, but explain what is still in progress and what you would like feedback on. Start the PR title with "WIP" to indicate this.
diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml
index a7a42bde..5591cb45 100644
--- a/.github/release-drafter.yml
+++ b/.github/release-drafter.yml
@@ -6,9 +6,9 @@ categories:
- title: 🐛 Bug Fixes
label: Bug
- title: 🧰 Improvements
- label: Improvement
+ label: Improvement
- title: down arrow Dependency Updates
- label: Dependencies
+ label: Dependencies
change-template: '- $TITLE (#$NUMBER)'
version-resolver:
major:
@@ -23,5 +23,5 @@ version-resolver:
default: patch
template: |
## Other Changes
-
+
$CHANGES
diff --git a/.github/workflows/Zapier.yml b/.github/workflows/Zapier.yml
index 3665dd58..5aab0bbf 100644
--- a/.github/workflows/Zapier.yml
+++ b/.github/workflows/Zapier.yml
@@ -7,7 +7,7 @@ on:
# Triggers the workflow on push or pull request events but only for the "main" branch
issues:
types: [closed]
-
+
permissions:
issues: read
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index af204294..eac8cfbf 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2,20 +2,20 @@ name: Test
on:
pull_request:
- branches: "**"
+ branches: '**'
jobs:
build:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v3
- - name: "[Setup] Node"
+ - name: '[Setup] Node'
uses: actions/setup-node@v3
with:
node-version: 16
- - name: "[Setup] Dependencies"
+ - name: '[Setup] Dependencies'
run: yarn
- - name: "[Test] Linting"
+ - name: '[Test] Linting'
run: yarn lint
- name: Unit tests results
diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml
index a64b3721..82e66d26 100644
--- a/.github/workflows/release-drafter.yml
+++ b/.github/workflows/release-drafter.yml
@@ -1,4 +1,3 @@
-
name: Release Drafter
on:
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e13790dd..282a6ee1 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -3,6 +3,7 @@
:+1::tada: First off, thanks for taking the time to contribute! :tada::+1:
### How to Contribute
+
We love the open source community and enjoy the support and contributions of many of our users. We ask that any potential contributors to the SDK Follow the following guidelines:
If your proposed contribution is a small bug fix, please feel free to create your own fork of the repository and create a pull request.
@@ -10,13 +11,15 @@ If your proposed contribution is a small bug fix, please feel free to create you
If your contribution would _break_ or _change_ the functionality of the SDK, please reach out to us on (contact) before you put in a lot of effort into a change we may not be able to use. We try our best to make sure that the SDK remains stable so that developers do not have to continually change their code, however some breaking changes _are_ desirable, so please get in touch to discuss your idea before you put in a lot of effort.
#### Reporting Bugs
-If you have found a bug with the SDK, please feel free to open an Issue.
+
+If you have found a bug with the SDK, please feel free to open an Issue.
If you are pretty certain that the issue is only related to the native iOS SDK, please open the issue in our [native iOS SDK repository](https://github.com/OneSignal/OneSignal-iOS-SDK).
If you are certain the issue is contained to the Android SDK, please open the issue in our [Android SDK repository](https://github.com/OneSignal/OneSignal-Android-SDK)
#### Before Submitting A Bug Report
+
Before creating bug reports, please check this list of steps to follow.
1. Make sure that you are actually encountering an _issue_ and not a _question_. If you simply have a question about the SDK, we would be more than happy to assist you in our Support section on the web (https://www.onesignal.com - click the Message button at the bottom right)
@@ -24,10 +27,10 @@ Before creating bug reports, please check this list of steps to follow.
> **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one.
-
#### How Do I Submit a Good Bug Report
-* **Use a clear and descriptive title** for the issue to identify the problem.
-* **Include Reproducibility** It is nearly always a good idea to include steps to reproduct the issue. If you cannot reliably reproduce the issue yourself, that's ok, but reproducible steps help best.
-* **Describe your environment**, tell us what version of react-native your app is using, what version of the react-native-onesignal SDK you're using, how you added it to your project, and so on.
-* **Include a Stack Trace** If your issue involves a crash/exception, ***PLEASE*** post the stack trace to help us identify the root issue.
-* **Include an Example Project** This isn't required, but if you want your issue fixed quickly, it's often a good idea to include an example project as a zip and include it with the issue. You can also download the Demo project (included in the `/examples` folder of this repo) and set up an example project with this code as a starting point.
+
+- **Use a clear and descriptive title** for the issue to identify the problem.
+- **Include Reproducibility** It is nearly always a good idea to include steps to reproduct the issue. If you cannot reliably reproduce the issue yourself, that's ok, but reproducible steps help best.
+- **Describe your environment**, tell us what version of react-native your app is using, what version of the react-native-onesignal SDK you're using, how you added it to your project, and so on.
+- **Include a Stack Trace** If your issue involves a crash/exception, **_PLEASE_** post the stack trace to help us identify the root issue.
+- **Include an Example Project** This isn't required, but if you want your issue fixed quickly, it's often a good idea to include an example project as a zip and include it with the issue. You can also download the Demo project (included in the `/examples` folder of this repo) and set up an example project with this code as a starting point.
diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md
index 9095189a..3d1588c9 100644
--- a/MIGRATION_GUIDE.md
+++ b/MIGRATION_GUIDE.md
@@ -18,25 +18,26 @@ A user is a new concept which is meant to represent your end-user. A user has ze
## Subscription
-A subscription refers to the method in which an end-user can receive various communications sent by OneSignal, including push notifications, SMS, and email. In previous versions of the OneSignal platform, each of these channels was referred to as a “player”. A subscription is in fact identical to the legacy “player” concept. Each subscription has a **subscription_id** (previously, player_id) to uniquely identify that communication channel.
+A subscription refers to the method in which an end-user can receive various communications sent by OneSignal, including push notifications, SMS, and email. In previous versions of the OneSignal platform, each of these channels was referred to as a “player”. A subscription is in fact identical to the legacy “player” concept. Each subscription has a **subscription_id** (previously, player_id) to uniquely identify that communication channel.
## Aliases
-Aliases are a concept evolved from [external user ids](https://documentation.onesignal.com/docs/external-user-ids) which allows the unique identification of a user within a OneSignal application. Aliases are a key-value pair made up of an **alias label** (the key) and an **alias id** (the value). The **alias label** can be thought of as a consistent keyword across all users, while the **alias id** is a value specific to each user for that particular label. The combined **alias label** and **alias id** provide uniqueness to successfully identify a user.
+Aliases are a concept evolved from [external user ids](https://documentation.onesignal.com/docs/external-user-ids) which allows the unique identification of a user within a OneSignal application. Aliases are a key-value pair made up of an **alias label** (the key) and an **alias id** (the value). The **alias label** can be thought of as a consistent keyword across all users, while the **alias id** is a value specific to each user for that particular label. The combined **alias label** and **alias id** provide uniqueness to successfully identify a user.
-OneSignal uses a built-in **alias label** called `external_id` which supports existing use of [external user ids](https://documentation.onesignal.com/docs/external-user-ids). `external_id` is also used as the identification method when a user identifies themselves to the OneSignal SDK via `OneSignal.login`. Multiple aliases can be created for each user to allow for your own application's unique identifier as well as identifiers from other integrated applications.
+OneSignal uses a built-in **alias label** called `external_id` which supports existing use of [external user ids](https://documentation.onesignal.com/docs/external-user-ids). `external_id` is also used as the identification method when a user identifies themselves to the OneSignal SDK via `OneSignal.login`. Multiple aliases can be created for each user to allow for your own application's unique identifier as well as identifiers from other integrated applications.
# Migration Guide (v3 to v5)
The React Native SDK accesses the OneSignal native iOS and Android SDKs. For this update, all SDK versions are aligning across OneSignal’s suite of client SDKs. As such, the React Native SDK is making the jump from `v3` to `v5`.
# API Changes
+
## Namespaces
The OneSignal SDK has been updated to be more modular in nature. The SDK has been split into namespaces, and functionality previously in the static `OneSignal` class has been moved to the appropriate namespace. The namespaces and how to access them in code are as follows:
| **Namespace** | **Access Pattern** |
-| ------------- | -------------------------- |
+| -------------- | -------------------------- |
| Debug | `OneSignal.Debug` |
| InAppMessages | `OneSignal.InAppMessages` |
| LiveActivities | `OneSignal.LiveActivities` |
@@ -53,23 +54,22 @@ Navigate to your index.ts file, or the first Javascript file that loads with you
Replace the following:
-
```typescript
- OneSignal.setAppId("YOUR_ONESIGNAL_APP_ID");
+OneSignal.setAppId('YOUR_ONESIGNAL_APP_ID');
```
To the match the new initialization:
```typescript
- OneSignal.initialize("YOUR_ONESIGNAL_APP_ID");
+OneSignal.initialize('YOUR_ONESIGNAL_APP_ID');
```
-If your integration is **not** user-centric, there is no additional startup code required. A device-scoped user *(please see definition of “**device-scoped user**” below in Glossary)* is automatically created as part of the push subscription creation, both of which are only accessible from the current device or through the OneSignal dashboard.
+If your integration is **not** user-centric, there is no additional startup code required. A device-scoped user _(please see definition of “**device-scoped user**” below in Glossary)_ is automatically created as part of the push subscription creation, both of which are only accessible from the current device or through the OneSignal dashboard.
If your integration is user-centric, or you want the ability to identify the user beyond the current device, the `login` method should be called to identify the user:
```typescript
- OneSignal.User.login("USER_EXTERNAL_ID");
+OneSignal.User.login('USER_EXTERNAL_ID');
```
The `login` method will associate the device’s push subscription to the user that can be identified via the alias `externalId=USER_EXTERNAL_ID`. If that user doesn’t already exist, it will be created. If the user does already exist, the user will be updated to own the device’s push subscription. Note that the push subscription for the device will always be transferred to the newly logged in user, as that user is the current owner of that push subscription.
@@ -77,7 +77,7 @@ The `login` method will associate the device’s push subscription to the user t
Once (or if) the user is no longer identifiable in your app (i.e. they logged out), the `logout` method should be called:
```typescript
- OneSignal.User.logout();
+OneSignal.User.logout();
```
Logging out has the affect of reverting to a device-scoped user, which is the new owner of the device’s push subscription.
@@ -87,12 +87,15 @@ Logging out has the affect of reverting to a device-scoped user, which is the ne
In previous versions of the SDK, a “player” could have up to one email address and up to one phone number for SMS. In the user-centered model, a user can own the current device’s **Push Subscription** along with the ability to have **zero or more** email subscriptions and **zero or more** SMS subscriptions. Note: If a new user logs in via the `login` method, the previous user will no longer own that push subscription.
### **Push Subscription**
+
The current device’s push subscription can be retrieved via:
```typescript
- const id: string = await OneSignal.User.PushSubscription.getPushSubscriptionId();
- const token: string = await OneSignal.User.PushSubscription.getPushSubscriptionToken();
- const optedIn: boolean = await OneSignal.User.PushSubscription.getOptedIn();
+const id: string =
+ await OneSignal.User.PushSubscription.getPushSubscriptionId();
+const token: string =
+ await OneSignal.User.PushSubscription.getPushSubscriptionToken();
+const optedIn: boolean = await OneSignal.User.PushSubscription.getOptedIn();
```
### **Opting In and Out of Push Notifications**
@@ -102,13 +105,13 @@ To receive push notifications on the device, call the push subscription’s `opt
Note: For greater control over prompting for push notification permission, you may use the `OneSignal.Notifications.requestPermission` method detailed below in the API Reference.
```typescript
- OneSignal.User.PushSubscription.optIn();
+OneSignal.User.PushSubscription.optIn();
```
If at any point you want the user to stop receiving push notifications on the current device (regardless of system-level permission status), you can use the push subscription to opt out:
```typescript
- OneSignal.User.PushSubscription.optOut();
+OneSignal.User.PushSubscription.optOut();
```
To resume receiving of push notifications (driving the native permission prompt if permissions are not available), you can opt back in with the `optIn` method from above.
@@ -118,15 +121,15 @@ To resume receiving of push notifications (driving the native permission prompt
Email and/or SMS subscriptions can be added or removed via the following methods. The remove methods will result in a no-op if the specified email or SMS number does not exist on the user within the SDK, and no request will be made.
```typescript
- // Add email subscription
- OneSignal.User.addEmail("customer@company.com");
- // Remove previously added email subscription
- OneSignal.User.removeEmail("customer@company.com");
-
- // Add SMS subscription
- OneSignal.User.addSms("+15558675309");
- // Remove previously added SMS subscription
- OneSignal.User.removeSms("+15558675309");
+// Add email subscription
+OneSignal.User.addEmail('customer@company.com');
+// Remove previously added email subscription
+OneSignal.User.removeEmail('customer@company.com');
+
+// Add SMS subscription
+OneSignal.User.addSms('+15558675309');
+// Remove previously added SMS subscription
+OneSignal.User.removeSms('+15558675309');
```
# API Reference
@@ -137,16 +140,14 @@ Below is a comprehensive reference to the `5.0.0-beta-02` OneSignal React Native
The SDK is still accessible via a `OneSignal` static class. It provides access to higher level functionality and is a gateway to each subspace of the SDK.
-|**React Native** | **Description** |
-|-----------------------------------------------------------------------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `OneSignal.initialize("YOUR_ONESIGNAL_APP_ID")` | *Initializes the OneSignal SDK. This should be called during startup of the application.* |
-| `OneSignal.User.login("USER_EXTERNAL_ID")` | *Login to OneSignal under the user identified by the [externalId] provided. The act of logging a user into the OneSignal SDK will switch the [user] context to that specific user.
- If the [externalId] exists, the user will be retrieved and the context will be set from that user information. If operations have already been performed under a device-scoped user, they ***will not*** be applied to the now logged in user (they will be lost). - If the [externalId] does not exist the user, the user will be created and the context set from the current local state. If operations have already been performed under a device-scoped user, those operations ***will*** be applied to the newly created user.
***Push Notifications and In App Messaging*** Logging in a new user will automatically transfer the push notification and in app messaging subscription from the current user (if there is one) to the newly logged in user. This is because both push notifications and in-app messages are owned by the device.* |
-| `OneSignal.User.logout()` | *Logout the user previously logged in via [login]. The [user] property now references a new device-scoped user. A device-scoped user has no user identity that can later be retrieved, except through this device as long as the app remains installed and the app data is not cleared.* |
-| `OneSignal.setConsentGiven(true)` | *Indicates whether privacy consent has been granted. This field is only relevant when the application has opted into data privacy protections. See [requiresPrivacyConsent].* |
-| `OneSignal.setConsentRequired(true)` | *Determines whether a user must consent to privacy prior to their user data being sent up to OneSignal. This should be set to `true` prior to the invocation of `initialize` to ensure compliance.* |
-| `OneSignal.setLaunchURLsInApp(true)` | *This method can be used to set if launch URLs should be opened in safari or within the application. Set to `true` to launch all notifications with a URL in the app instead of the default web browser. Make sure to call `setLaunchURLsInApp` before the `initialize` call.* |
-
-
+| **React Native** | **Description** |
+| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `OneSignal.initialize("YOUR_ONESIGNAL_APP_ID")` | _Initializes the OneSignal SDK. This should be called during startup of the application._ |
+| `OneSignal.User.login("USER_EXTERNAL_ID")` | \*Login to OneSignal under the user identified by the [externalId] provided. The act of logging a user into the OneSignal SDK will switch the [user] context to that specific user.
- If the [externalId] exists, the user will be retrieved and the context will be set from that user information. If operations have already been performed under a device-scoped user, they **_will not_** be applied to the now logged in user (they will be lost). - If the [externalId] does not exist the user, the user will be created and the context set from the current local state. If operations have already been performed under a device-scoped user, those operations **_will_** be applied to the newly created user.
**_Push Notifications and In App Messaging_** Logging in a new user will automatically transfer the push notification and in app messaging subscription from the current user (if there is one) to the newly logged in user. This is because both push notifications and in-app messages are owned by the device.\* |
+| `OneSignal.User.logout()` | _Logout the user previously logged in via [login]. The [user] property now references a new device-scoped user. A device-scoped user has no user identity that can later be retrieved, except through this device as long as the app remains installed and the app data is not cleared._ |
+| `OneSignal.setConsentGiven(true)` | _Indicates whether privacy consent has been granted. This field is only relevant when the application has opted into data privacy protections. See [requiresPrivacyConsent]._ |
+| `OneSignal.setConsentRequired(true)` | _Determines whether a user must consent to privacy prior to their user data being sent up to OneSignal. This should be set to `true` prior to the invocation of `initialize` to ensure compliance._ |
+| `OneSignal.setLaunchURLsInApp(true)` | _This method can be used to set if launch URLs should be opened in safari or within the application. Set to `true` to launch all notifications with a URL in the app instead of the default web browser. Make sure to call `setLaunchURLsInApp` before the `initialize` call._ |
## Live Activities Namespace
@@ -154,70 +155,66 @@ Live Activities are a type of interactive push notification. Apple introduced th
Please refer to OneSignal’s guide on [Live Activities](https://documentation.onesignal.com/docs/live-activities), the [Live Activities Quickstart](https://documentation.onesignal.com/docs/live-activities-quickstart) tutorial, and the [existing SDK reference](https://documentation.onesignal.com/docs/sdk-reference#live-activities) on Live Activities.
-|**React Native** | **Description** |
-| --------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
-| `OneSignal.LiveActivities.enter("ACTIVITY_ID", "TOKEN")`
***See below for usage of callbacks*** | *Entering a Live Activity associates an `activityId` with a live activity temporary push `token` on OneSignal's server. The activityId is then used with the OneSignal REST API to update one or multiple Live Activities at one time.* |
-| `OneSignal.LiveActivities.exit("ACTIVITY_ID")`
***See below for usage of callbacks*** | *Exiting a Live activity deletes the association between a customer defined `activityId` with a Live Activity temporary push `token` on OneSignal's server.* |
+| **React Native** | **Description** |
+| ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `OneSignal.LiveActivities.enter("ACTIVITY_ID", "TOKEN")`
**_See below for usage of callbacks_** | _Entering a Live Activity associates an `activityId` with a live activity temporary push `token` on OneSignal's server. The activityId is then used with the OneSignal REST API to update one or multiple Live Activities at one time._ |
+| `OneSignal.LiveActivities.exit("ACTIVITY_ID")`
**_See below for usage of callbacks_** | _Exiting a Live activity deletes the association between a customer defined `activityId` with a Live Activity temporary push `token` on OneSignal's server._ |
+
```typescript
- // Enter a Live Activity
- OneSignal.LiveActivities.enter("ACTIVITY_ID", "TOKEN", (results) => {
- console.log("Results of entering live activity");
- console.log(results);
- });
-
- // Exit a Live Activity
- OneSignal.LiveActivities.exit("ACTIVITY_ID", (results) => {
- console.log("Results of exiting live activity");
- console.log(results);
- });
+// Enter a Live Activity
+OneSignal.LiveActivities.enter('ACTIVITY_ID', 'TOKEN', (results) => {
+ console.log('Results of entering live activity');
+ console.log(results);
+});
+
+// Exit a Live Activity
+OneSignal.LiveActivities.exit('ACTIVITY_ID', (results) => {
+ console.log('Results of exiting live activity');
+ console.log(results);
+});
```
## User Namespace
The User namespace is accessible via `OneSignal.User` and provides access to user-scoped functionality.
-
-|**React Native** | **Description** |
-|------------------------------------------------------------------------------------------| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `OneSignal.User.setLanguage("en")` | *Set the 2-character language for this user.* |
-| `OneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID")` | *Set an alias for the current user. If this alias label already exists on this user, it will be overwritten with the new alias id.* |
-| `OneSignal.User.addAliases({ALIAS_LABEL_01: "ALIAS_ID_01", ALIAS_LABEL_02: "ALIAS_ID_02"})` | *Set aliases for the current user. If any alias already exists, it will be overwritten to the new values.* |
-| `OneSignal.User.removeAlias("ALIAS_LABEL")` | *Remove an alias from the current user.* |
-| `OneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02"]])` | *Remove aliases from the current user.* |
-| `OneSignal.User.addEmail("customer@company.com")` | *Add a new email subscription to the current user.* |
-| `OneSignal.User.removeEmail("customer@company.com")` | *Results in a no-op if the specified email does not exist on the user within the SDK, and no request will be made.* |
-| `OneSignal.User.addSms("+15558675309")` | *Add a new SMS subscription to the current user.* |
-| `OneSignal.User.removeSms("+15558675309")` | *Results in a no-op if the specified phone number does not exist on the user within the SDK, and no request will be made..* |
-| `OneSignal.User.addTag("KEY", "VALUE")` | *Add a tag for the current user. Tags are key:value pairs used as building blocks for targeting specific users and/or personalizing messages. If the tag key already exists, it will be replaced with the value provided here.* |
-| `OneSignal.User.addTags({"KEY_01": "VALUE_01", "KEY_02": "VALUE_02"})` | *Add multiple tags for the current user. Tags are key:value pairs used as building blocks for targeting specific users and/or personalizing messages. If the tag key already exists, it will be replaced with the value provided here.* |
-| `OneSignal.User.removeTag("KEY")` | *Remove the data tag with the provided key from the current user.* |
-| `OneSignal.User.removeTags(["KEY_01", "KEY_02"])` | *Remove multiple tags with the provided keys from the current user.* |
-
-
+| **React Native** | **Description** |
+| ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `OneSignal.User.setLanguage("en")` | _Set the 2-character language for this user._ |
+| `OneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID")` | _Set an alias for the current user. If this alias label already exists on this user, it will be overwritten with the new alias id._ |
+| `OneSignal.User.addAliases({ALIAS_LABEL_01: "ALIAS_ID_01", ALIAS_LABEL_02: "ALIAS_ID_02"})` | _Set aliases for the current user. If any alias already exists, it will be overwritten to the new values._ |
+| `OneSignal.User.removeAlias("ALIAS_LABEL")` | _Remove an alias from the current user._ |
+| `OneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02"]])` | _Remove aliases from the current user._ |
+| `OneSignal.User.addEmail("customer@company.com")` | _Add a new email subscription to the current user._ |
+| `OneSignal.User.removeEmail("customer@company.com")` | _Results in a no-op if the specified email does not exist on the user within the SDK, and no request will be made._ |
+| `OneSignal.User.addSms("+15558675309")` | _Add a new SMS subscription to the current user._ |
+| `OneSignal.User.removeSms("+15558675309")` | _Results in a no-op if the specified phone number does not exist on the user within the SDK, and no request will be made.._ |
+| `OneSignal.User.addTag("KEY", "VALUE")` | _Add a tag for the current user. Tags are key:value pairs used as building blocks for targeting specific users and/or personalizing messages. If the tag key already exists, it will be replaced with the value provided here._ |
+| `OneSignal.User.addTags({"KEY_01": "VALUE_01", "KEY_02": "VALUE_02"})` | _Add multiple tags for the current user. Tags are key:value pairs used as building blocks for targeting specific users and/or personalizing messages. If the tag key already exists, it will be replaced with the value provided here._ |
+| `OneSignal.User.removeTag("KEY")` | _Remove the data tag with the provided key from the current user._ |
+| `OneSignal.User.removeTags(["KEY_01", "KEY_02"])` | _Remove multiple tags with the provided keys from the current user._ |
## Push Subscription Namespace
The Push Subscription namespace is accessible via `OneSignal.User.pushSubscription` and provides access to push subscription-scoped functionality.
-
-|**React Native** | **Description** |
-|------------------------------------------------------------------------------------------------------------------------------------------------| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `await OneSignal.User.PushSubscription.getId()` | *The readonly push subscription ID.* |
-| `await OneSignal.User.PushSubscription.getToken()` | *The readonly push token.* |
-| `await OneSignal.User.PushSubscription.getOptedIn()` | *Gets a boolean value indicating whether the current user is opted in to push notifications. This returns `true` when the app has notifications permission and `optedOut` is called. ***Note:*** Does not take into account the existence of the subscription ID and push token. This boolean may return `true` but push notifications may still not be received by the user.* |
-| `OneSignal.User.PushSubscription.optIn()` | *Call this method to receive push notifications on the device or to resume receiving of push notifications after calling `optOut`. If needed, this method will prompt the user for push notifications permission.* |
-| `OneSignal.User.PushSubscription.optOut()` | *If at any point you want the user to stop receiving push notifications on the current device (regardless of system-level permission status), you can call this method to opt out.* |
-| `OneSignal.User.PushSubscription.addObserver(observer: (event) => void)`
***See below for usage*** | *The `OSPushSubscriptionObserver.onOSPushSubscriptionChanged` method will be fired on the passed-in object when the push subscription changes. This method returns the current `OSPushSubscriptionState` at the time of adding this observer.* |
-| `OneSignal.User.PushSubscription.removeObserver(observer)`
***See below for usage*** | *Remove a push subscription observer that has been previously added.* |
+| **React Native** | **Description** |
+| --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `await OneSignal.User.PushSubscription.getId()` | _The readonly push subscription ID._ |
+| `await OneSignal.User.PushSubscription.getToken()` | _The readonly push token._ |
+| `await OneSignal.User.PushSubscription.getOptedIn()` | \*Gets a boolean value indicating whether the current user is opted in to push notifications. This returns `true` when the app has notifications permission and `optedOut` is called. **_Note:_** Does not take into account the existence of the subscription ID and push token. This boolean may return `true` but push notifications may still not be received by the user.\* |
+| `OneSignal.User.PushSubscription.optIn()` | _Call this method to receive push notifications on the device or to resume receiving of push notifications after calling `optOut`. If needed, this method will prompt the user for push notifications permission._ |
+| `OneSignal.User.PushSubscription.optOut()` | _If at any point you want the user to stop receiving push notifications on the current device (regardless of system-level permission status), you can call this method to opt out._ |
+| `OneSignal.User.PushSubscription.addObserver(observer: (event) => void)`
**_See below for usage_** | _The `OSPushSubscriptionObserver.onOSPushSubscriptionChanged` method will be fired on the passed-in object when the push subscription changes. This method returns the current `OSPushSubscriptionState` at the time of adding this observer._ |
+| `OneSignal.User.PushSubscription.removeObserver(observer)`
**_See below for usage_** | _Remove a push subscription observer that has been previously added._ |
### Push Subscription Observer
Any object implementing the `OSPushSubscriptionObserver` protocol can be added as an observer. You can call `removeObserver` to remove any existing listeners.
-
```typescript
// Create an observer
-OneSignal.User.PushSubscription.addObserver(subscription => {
+OneSignal.User.PushSubscription.addObserver((subscription) => {
console.log('OneSignal: subscription changed: ', subscription);
});
@@ -229,48 +226,46 @@ OneSignal.User.PushSubscription.removeObserver(subscription);
The Session namespace is accessible via `OneSignal.Session` and provides access to session-scoped functionality.
-
-|**React Native** | **Description** |
-| --------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
-| `OneSignal.Session.addOutcome("OUTCOME_NAME")` | *Add an outcome with the provided name, captured against the current session.* |
-| `OneSignal.Session.addUniqueOutcome("OUTCOME_NAME")` | *Add a unique outcome with the provided name, captured against the current session.* |
-| `OneSignal.Session.addOutcomeWithValue("OUTCOME_NAME", 1)` | *Add an outcome with the provided name and value, captured against the current session.* |
-
-
+| **React Native** | **Description** |
+| ---------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
+| `OneSignal.Session.addOutcome("OUTCOME_NAME")` | _Add an outcome with the provided name, captured against the current session._ |
+| `OneSignal.Session.addUniqueOutcome("OUTCOME_NAME")` | _Add a unique outcome with the provided name, captured against the current session._ |
+| `OneSignal.Session.addOutcomeWithValue("OUTCOME_NAME", 1)` | _Add an outcome with the provided name and value, captured against the current session._ |
## Notifications Namespace
The Notifications namespace is accessible via `OneSignal.Notifications` and provides access to notification-scoped functionality.
-|**React Native** | **Description** |
-|----------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------|
-| `await OneSignal.Notifications.hasPermission()` | *Whether this app has push notification permission.* |
-| `await OneSignal.Notifications.canRequestPermission()` | *Whether attempting to request notification permission will show a prompt. Returns `true` if the device has not been prompted for push notification permission already.* | `await OneSignal.Notifications.permissionNative()` | *(ios only) Returns the enum for the native permission of the device. It will be one of: NotDetermined, Denied, Authorized, Provisional (only available in iOS 12), Ephemeral (only available in iOS 14) * |
-| `OneSignal.Notifications.clearAll();` | *Removes all OneSignal notifications.*|
-| `OneSignal.Notifications.removeNotification("NOTIFICATION_ID")` | *(Android only) Cancels a single OneSignal notification based on its Android notification integer ID. Use instead of Android's [android.app.NotificationManager.cancel], otherwise the notification will be restored when your app is restarted.*|
-| `OneSignal.Notifications.removeGroupedNotifications("GROUP_KEY")` | *(Android only) Cancels a group of OneSignal notifications with the provided group key. Grouping notifications is a OneSignal concept, there is no [android.app.NotificationManager] equivalent.*|
-| `OneSignal.Notifications.requestPermission()`
***See below for usage*** | *Prompt the user for permission to receive push notifications. This will display the native system prompt to request push notification permission.* |
-| `OneSignal.Notifications.registerForProvisionalAuthorization()` | *(iOS only) Instead of having to prompt the user for permission to send them push notifications, your app can request provisional authorization.*|
-| `OneSignal.Notifications.addPermissionObserver(observer)`
***See below for usage*** | *This method will fire when a notification permission setting changes. This happens when the user enables or disables notifications for your app from the system settings outside of your app.*|
-| `OneSignal.Notifications.removePermissionObserver(observer)`
***See below for usage*** | *Remove a push permission observer that has been previously added.*|
-| `OneSignal.Notifications.addEventListener("foregroundWillDisplay", (event) => {};)`
***See below for usage*** | *Sets the handler to run before displaying a notification while the app is in focus. Use this handler to read notification data and change it or decide if the notification ***should*** show or not.
***Note:*** this runs ***after*** the [Notification Service Extension](https://documentation.onesignal.com/docs/service-extensions) which can be used to modify the notification before showing it.* |
-| `OneSignal.Notifications.addEventListener("click", (event) => {};)`
***See below for usage*** | *Sets a handler that will run whenever a notification is opened by the user.*|
-
+| **React Native** | **Description** |
+| -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `await OneSignal.Notifications.hasPermission()` | _Whether this app has push notification permission._ |
+| `await OneSignal.Notifications.canRequestPermission()` | _Whether attempting to request notification permission will show a prompt. Returns `true` if the device has not been prompted for push notification permission already._ | `await OneSignal.Notifications.permissionNative()` | _(ios only) Returns the enum for the native permission of the device. It will be one of: NotDetermined, Denied, Authorized, Provisional (only available in iOS 12), Ephemeral (only available in iOS 14) _ |
+| `OneSignal.Notifications.clearAll();` | _Removes all OneSignal notifications._ |
+| `OneSignal.Notifications.removeNotification("NOTIFICATION_ID")` | _(Android only) Cancels a single OneSignal notification based on its Android notification integer ID. Use instead of Android's [android.app.NotificationManager.cancel], otherwise the notification will be restored when your app is restarted._ |
+| `OneSignal.Notifications.removeGroupedNotifications("GROUP_KEY")` | _(Android only) Cancels a group of OneSignal notifications with the provided group key. Grouping notifications is a OneSignal concept, there is no [android.app.NotificationManager] equivalent._ |
+| `OneSignal.Notifications.requestPermission()`
**_See below for usage_** | _Prompt the user for permission to receive push notifications. This will display the native system prompt to request push notification permission._ |
+| `OneSignal.Notifications.registerForProvisionalAuthorization()` | _(iOS only) Instead of having to prompt the user for permission to send them push notifications, your app can request provisional authorization._ |
+| `OneSignal.Notifications.addPermissionObserver(observer)`
**_See below for usage_** | _This method will fire when a notification permission setting changes. This happens when the user enables or disables notifications for your app from the system settings outside of your app._ |
+| `OneSignal.Notifications.removePermissionObserver(observer)`
**_See below for usage_** | _Remove a push permission observer that has been previously added._ |
+| `OneSignal.Notifications.addEventListener("foregroundWillDisplay", (event) => {};)`
**_See below for usage_** | \*Sets the handler to run before displaying a notification while the app is in focus. Use this handler to read notification data and change it or decide if the notification **_should_** show or not.
**_Note:_** this runs **_after_** the [Notification Service Extension](https://documentation.onesignal.com/docs/service-extensions) which can be used to modify the notification before showing it.\* |
+| `OneSignal.Notifications.addEventListener("click", (event) => {};)`
**_See below for usage_** | _Sets a handler that will run whenever a notification is opened by the user._ |
### Prompt for Push Notification Permission
+
```typescript
-OneSignal.Notifications.requestPermission(accepted => {
- console.log("User accepted notifications: " + accepted);
+OneSignal.Notifications.requestPermission((accepted) => {
+ console.log('User accepted notifications: ' + accepted);
});
```
### Permission Observer
+
Add an observer when permission status changes. You can call `removePermissionObserver` to remove any existing listeners.
```typescript
// Add an observer
-let observer = function(req) {
- console.log("OneSignal: permission state changed to: " + (req));
+let observer = function (req) {
+ console.log('OneSignal: permission state changed to: ' + req);
};
OneSignal.Notifications.addPermissionObserver(observer);
@@ -279,98 +274,110 @@ OneSignal.Notifications.removePermissionObserver(observer);
```
### Notification Lifecycle Listener
+
```typescript
-OneSignal.Notifications.addEventListener("foregroundWillDisplay", (event) => {
- event.preventDefault();
- // some async work
-
- // Use display() to display the notification after some async work
- event.getNotification().display();
+OneSignal.Notifications.addEventListener('foregroundWillDisplay', (event) => {
+ event.preventDefault();
+ // some async work
+
+ // Use display() to display the notification after some async work
+ event.getNotification().display();
});
```
### Notification Click Listener
+
```typescript
-OneSignal.Notifications.addEventListener("click", (event) => {
- console.log('OneSignal: notification clicked: ' + event);
+OneSignal.Notifications.addEventListener('click', (event) => {
+ console.log('OneSignal: notification clicked: ' + event);
});
```
## Location Namespace
+
The Location namespace is accessible via `OneSignal.Location` and provide access to location-scoped functionality.
-|**React Native** | **Description** |
-|-------------------------------------------------------------------------|-------------------------------------------------------------------------------------------|
-| `await OneSignal.Location.isShared()`
***See below for usage*** | *Whether location is currently shared with OneSignal.*|
-| `OneSignal.Location.requestPermission()` | *Use this method to manually prompt the user for location permissions. This allows for geotagging so you send notifications to users based on location.* |
+| **React Native** | **Description** |
+| ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `await OneSignal.Location.isShared()`
**_See below for usage_** | _Whether location is currently shared with OneSignal._ |
+| `OneSignal.Location.requestPermission()` | _Use this method to manually prompt the user for location permissions. This allows for geotagging so you send notifications to users based on location._ |
### isShared method
+
```typescript
const shared: boolean = await OneSignal.Location.isShared();
-console.log("Location shared: ", shared);
+console.log('Location shared: ', shared);
```
## InAppMessages Namespace
+
The In App Messages namespace is accessible via `OneSignal.InAppMessages` and provide access to in app messages-scoped functionality.
-| | **Description** |
-|------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------|
-| `await OneSignal.InAppMessages.getPaused()`
***See below for usage***
`OneSignal.InAppMessages.setPaused(true)` | *Whether in-app messaging is currently paused. When set to `true`, no IAM will be presented to the user regardless of whether they qualify for them. When set to `false`, any IAMs the user qualifies for will be presented to the user at the appropriate time.* |
-| `OneSignal.InAppMessages.addTrigger("triggerKey", "triggerValue")` | *Add a trigger for the current user. Triggers are currently explicitly used to determine whether a specific IAM should be displayed to the user. See [Triggers](https://documentation.onesignal.com/docs/iam-triggers).
If the trigger key already exists, it will be replaced with the value provided here. Note that triggers are not persisted to the backend. They only exist on the local device and are applicable to the current user.* |
-| `OneSignal.InAppMessages.addTriggers({"triggerKey1":"triggerValue", "triggerKey2": "triggerValue"})` | *Add multiple triggers for the current user. Triggers are currently explicitly used to determine whether a specific IAM should be displayed to the user. See [Triggers](https://documentation.onesignal.com/docs/iam-triggers).
If any trigger key already exists, it will be replaced with the value provided here. Note that triggers are not persisted to the backend. They only exist on the local device and are applicable to the current user.* |
-| `OneSignal.InAppMessages.removeTrigger("triggerKey")` | *Remove the trigger with the provided key from the current user.* |
-| `OneSignal.InAppMessages.removeTriggers(["triggerKey1", "triggerKey2"])` | *Remove multiple triggers from the current user.* |
-| `OneSignal.InAppMessages.clearTriggers()` | *Clear all triggers from the current user.* |
-| ` OneSignal.InAppMessages.setLifecycleHandler(handlerObject)`
***See below for usage*** | *Set the in-app message lifecycle handler.* |
-| `OneSignal.InAppMessages.setClickHandler(handler)`
`OneSignal.InAppMessages.setPaused(true)` | _Whether in-app messaging is currently paused. When set to `true`, no IAM will be presented to the user regardless of whether they qualify for them. When set to `false`, any IAMs the user qualifies for will be presented to the user at the appropriate time._ |
+| `OneSignal.InAppMessages.addTrigger("triggerKey", "triggerValue")` | _Add a trigger for the current user. Triggers are currently explicitly used to determine whether a specific IAM should be displayed to the user. See [Triggers](https://documentation.onesignal.com/docs/iam-triggers).
If the trigger key already exists, it will be replaced with the value provided here. Note that triggers are not persisted to the backend. They only exist on the local device and are applicable to the current user._ |
+| `OneSignal.InAppMessages.addTriggers({"triggerKey1":"triggerValue", "triggerKey2": "triggerValue"})` | _Add multiple triggers for the current user. Triggers are currently explicitly used to determine whether a specific IAM should be displayed to the user. See [Triggers](https://documentation.onesignal.com/docs/iam-triggers).
If any trigger key already exists, it will be replaced with the value provided here. Note that triggers are not persisted to the backend. They only exist on the local device and are applicable to the current user._ |
+| `OneSignal.InAppMessages.removeTrigger("triggerKey")` | _Remove the trigger with the provided key from the current user._ |
+| `OneSignal.InAppMessages.removeTriggers(["triggerKey1", "triggerKey2"])` | _Remove multiple triggers from the current user._ |
+| `OneSignal.InAppMessages.clearTriggers()` | _Clear all triggers from the current user._ |
+| ` OneSignal.InAppMessages.setLifecycleHandler(handlerObject)`
**_See below for usage_** | _Set the in-app message lifecycle handler._ |
+| `OneSignal.InAppMessages.setClickHandler(handler)`
**_See below for usage_** | _Set the in-app message click handler._ |
### In-App Message isPaused method
+
```typescript
const paused = await OneSignal.InAppMessages.getPaused();
-console.log("IAM paused: ", paused);
+console.log('IAM paused: ', paused);
```
### In-App Message Click Listener
+
```typescript
-OneSignal.InAppMessages.addEventListener("click", (event) => {
+OneSignal.InAppMessages.addEventListener('click', (event) => {
console.log('OneSignal IAM clicked: ' + event);
});
```
### In-App Message Lifecycle Listeners
+
```typescript
-OneSignal.InAppMessages.addEventListener('willDisplay', (event) =>{
- console.log('OneSignal: will display IAM: ', event);
+OneSignal.InAppMessages.addEventListener('willDisplay', (event) => {
+ console.log('OneSignal: will display IAM: ', event);
});
-OneSignal.InAppMessages.addEventListener('didDisplay', (event) =>{
- console.log('OneSignal: did display IAM: ', event);
+OneSignal.InAppMessages.addEventListener('didDisplay', (event) => {
+ console.log('OneSignal: did display IAM: ', event);
});
-OneSignal.InAppMessages.addEventListener('willDismiss', (event) =>{
- console.log('OneSignal: will dismiss IAM: ', event);
+OneSignal.InAppMessages.addEventListener('willDismiss', (event) => {
+ console.log('OneSignal: will dismiss IAM: ', event);
});
-OneSignal.InAppMessages.addEventListener('didDismiss', (event) =>{
- console.log('OneSignal: did dismiss IAM: ', event);
+OneSignal.InAppMessages.addEventListener('didDismiss', (event) => {
+ console.log('OneSignal: did dismiss IAM: ', event);
});
```
## Debug Namespace
-The Debug namespace is accessible via `OneSignal.Debug` and provide access to debug-scoped functionality.
-| **React Native** | **Description** |
-| ---------------------------------------------- | ---------------------------------------------------------------------------------- |
-| `OneSignal.Debug.setLogLevel(6)` | *Sets the log level the OneSignal SDK should be writing to the Xcode log.* |
-| `OneSignal.Debug.setAlertLevel(0)` | *Sets the logging level to show as alert dialogs.* |
+The Debug namespace is accessible via `OneSignal.Debug` and provide access to debug-scoped functionality.
+| **React Native** | **Description** |
+| ---------------------------------- | -------------------------------------------------------------------------- |
+| `OneSignal.Debug.setLogLevel(6)` | _Sets the log level the OneSignal SDK should be writing to the Xcode log._ |
+| `OneSignal.Debug.setAlertLevel(0)` | _Sets the logging level to show as alert dialogs._ |
# Glossary
+
**device-scoped user**
-> An anonymous user with no aliases that cannot be retrieved except through the current device or OneSignal dashboard. On app install, the OneSignal SDK is initialized with a *device-scoped user*. A *device-scoped user* can be upgraded to an identified user by calling `OneSignal.login("USER_EXTERNAL_ID")` to identify the user by the specified external user ID.
+
+> An anonymous user with no aliases that cannot be retrieved except through the current device or OneSignal dashboard. On app install, the OneSignal SDK is initialized with a _device-scoped user_. A _device-scoped user_ can be upgraded to an identified user by calling `OneSignal.login("USER_EXTERNAL_ID")` to identify the user by the specified external user ID.
# Limitations
+
**General**
+
- Recommend using only in development and staging environments for Alpha releases
- Aliases will be available in a future release
- Outcomes will be available in a future release
@@ -378,6 +385,6 @@ The Debug namespace is accessible via `OneSignal.Debug` and provide access to de
- Any `User` namespace calls must be invoked **after** initialization. Example: `OneSignal.User.addTag("tag", "2")`
# Known issues
+
- Identity Verification
- - We will be introducing JWT in a follow-up Beta release
-
\ No newline at end of file
+ - We will be introducing JWT in a follow-up Beta release
diff --git a/README.md b/README.md
index 83694efb..8afe8682 100755
--- a/README.md
+++ b/README.md
@@ -3,6 +3,7 @@
### React Native OneSignal SDK
+
[![npm version](https://img.shields.io/npm/v/react-native-onesignal.svg)](https://www.npmjs.com/package/react-native-onesignal) [![npm downloads](https://img.shields.io/npm/dm/react-native-onesignal.svg)](https://www.npmjs.com/package/react-native-onesignal)
---
@@ -10,15 +11,18 @@
[OneSignal](https://onesignal.com/) is a free email, sms, push notification, and in-app message service for mobile apps. This SDK makes it easy to integrate your native React-Native iOS and/or Android apps with OneSignal.
#### Installation
+
See the [Setup Guide](https://documentation.onesignal.com/docs/react-native-sdk-setup) for setup instructions.
#### Change Log
+
See this repository's [release tags](https://github.com/OneSignal/react-native-onesignal/releases) for a complete change log of every released version.
#### Support
+
Please visit this repository's [Github issue tracker](https://github.com/OneSignal/react-native-onesignal/issues) for feature requests and bug reports related specifically to the SDK.
For account issues and support please contact OneSignal support from the [OneSignal.com](https://onesignal.com) dashboard.
#### Demo Project
-To make things easier, we have published demo projects in the `/examples` folder of this repository.
+To make things easier, we have published demo projects in the `/examples` folder of this repository.
diff --git a/examples/RNOneSignalTS/.watchmanconfig b/examples/RNOneSignalTS/.watchmanconfig
index 9e26dfee..0967ef42 100644
--- a/examples/RNOneSignalTS/.watchmanconfig
+++ b/examples/RNOneSignalTS/.watchmanconfig
@@ -1 +1 @@
-{}
\ No newline at end of file
+{}
diff --git a/examples/RNOneSignalTS/app.json b/examples/RNOneSignalTS/app.json
index 078c507b..2fc9ba3f 100644
--- a/examples/RNOneSignalTS/app.json
+++ b/examples/RNOneSignalTS/app.json
@@ -1,4 +1,4 @@
{
"name": "RNOneSignalTS",
"displayName": "RNOneSignalTS"
-}
\ No newline at end of file
+}
diff --git a/examples/RNOneSignalTS/ios/RNOneSignalTS/Images.xcassets/AppIcon.appiconset/Contents.json b/examples/RNOneSignalTS/ios/RNOneSignalTS/Images.xcassets/AppIcon.appiconset/Contents.json
index 118c98f7..48e64ae8 100644
--- a/examples/RNOneSignalTS/ios/RNOneSignalTS/Images.xcassets/AppIcon.appiconset/Contents.json
+++ b/examples/RNOneSignalTS/ios/RNOneSignalTS/Images.xcassets/AppIcon.appiconset/Contents.json
@@ -1,38 +1,38 @@
{
- "images" : [
+ "images": [
{
- "idiom" : "iphone",
- "size" : "29x29",
- "scale" : "2x"
+ "idiom": "iphone",
+ "size": "29x29",
+ "scale": "2x"
},
{
- "idiom" : "iphone",
- "size" : "29x29",
- "scale" : "3x"
+ "idiom": "iphone",
+ "size": "29x29",
+ "scale": "3x"
},
{
- "idiom" : "iphone",
- "size" : "40x40",
- "scale" : "2x"
+ "idiom": "iphone",
+ "size": "40x40",
+ "scale": "2x"
},
{
- "idiom" : "iphone",
- "size" : "40x40",
- "scale" : "3x"
+ "idiom": "iphone",
+ "size": "40x40",
+ "scale": "3x"
},
{
- "idiom" : "iphone",
- "size" : "60x60",
- "scale" : "2x"
+ "idiom": "iphone",
+ "size": "60x60",
+ "scale": "2x"
},
{
- "idiom" : "iphone",
- "size" : "60x60",
- "scale" : "3x"
+ "idiom": "iphone",
+ "size": "60x60",
+ "scale": "3x"
}
],
- "info" : {
- "version" : 1,
- "author" : "xcode"
+ "info": {
+ "version": 1,
+ "author": "xcode"
}
-}
\ No newline at end of file
+}
diff --git a/examples/RNOneSignalTS/ios/RNOneSignalTS/Images.xcassets/Contents.json b/examples/RNOneSignalTS/ios/RNOneSignalTS/Images.xcassets/Contents.json
index 2d92bd53..97a8662e 100644
--- a/examples/RNOneSignalTS/ios/RNOneSignalTS/Images.xcassets/Contents.json
+++ b/examples/RNOneSignalTS/ios/RNOneSignalTS/Images.xcassets/Contents.json
@@ -1,6 +1,6 @@
{
- "info" : {
- "version" : 1,
- "author" : "xcode"
+ "info": {
+ "version": 1,
+ "author": "xcode"
}
}
diff --git a/examples/RNOneSignalTS/src/App.tsx b/examples/RNOneSignalTS/src/App.tsx
index a94bc0cc..d4d8beea 100644
--- a/examples/RNOneSignalTS/src/App.tsx
+++ b/examples/RNOneSignalTS/src/App.tsx
@@ -27,7 +27,7 @@ const App = () => {
<>
-
+
>
);
@@ -38,7 +38,7 @@ const styles = StyleSheet.create({
flex: 1,
backgroundColor: Colors.white,
padding: 10,
- }
+ },
});
export default App;
diff --git a/examples/RNOneSignalTS/src/Helpers.tsx b/examples/RNOneSignalTS/src/Helpers.tsx
index 048303da..43406953 100644
--- a/examples/RNOneSignalTS/src/Helpers.tsx
+++ b/examples/RNOneSignalTS/src/Helpers.tsx
@@ -1,63 +1,72 @@
import * as React from 'react';
-import {View, StyleSheet, Platform, KeyboardAvoidingView, TextInput} from "react-native";
-import {Button} from "@react-native-material/core";
+import {
+ View,
+ StyleSheet,
+ Platform,
+ KeyboardAvoidingView,
+ TextInput,
+} from 'react-native';
+import {Button} from '@react-native-material/core';
const disabledColor = '#BEBEBE';
export const renderButtonView = (name: string, callback: Function) => {
- return (
-
-
- );
-}
+ return (
+
+
+ );
+};
-export const renderFieldView = (name: string, value: string, callback: (text: string) => void) => {
- return (
-
-
-
-
- );
-}
+export const renderFieldView = (
+ name: string,
+ value: string,
+ callback: (text: string) => void,
+) => {
+ return (
+
+
+
+ );
+};
const styles = StyleSheet.create({
- buttonContainer: {
- flexDirection: 'column',
- overflow: 'hidden',
- borderRadius: 10,
- marginVertical: 10,
- marginHorizontal: 10,
- },
- textInput: {
- marginHorizontal: 10,
- height: 40,
- },
+ buttonContainer: {
+ flexDirection: 'column',
+ overflow: 'hidden',
+ borderRadius: 10,
+ marginVertical: 10,
+ marginHorizontal: 10,
+ },
+ textInput: {
+ marginHorizontal: 10,
+ height: 40,
+ },
});
diff --git a/examples/RNOneSignalTS/src/OSButtons.tsx b/examples/RNOneSignalTS/src/OSButtons.tsx
index 6ac0b34b..7a377546 100644
--- a/examples/RNOneSignalTS/src/OSButtons.tsx
+++ b/examples/RNOneSignalTS/src/OSButtons.tsx
@@ -2,511 +2,487 @@ import {OneSignal, OutcomeEvent} from 'react-native-onesignal';
import * as React from 'react';
import {StyleSheet, View, Platform} from 'react-native';
import {renderButtonView} from './Helpers';
-import {Text, Divider} from "@react-native-material/core";
+import {Text, Divider} from '@react-native-material/core';
export interface Props {
- loggingFunction: Function;
- inputFieldValue: string;
+ loggingFunction: Function;
+ inputFieldValue: string;
}
class OSButtons extends React.Component {
- createInAppMessagesFields() {
- const {loggingFunction} = this.props;
-
- const getPausedButton = renderButtonView(
- 'Get paused',
- async () => {
- const paused = await OneSignal.InAppMessages.getPaused();
- loggingFunction(`Is IAM Paused: ${paused}`);
- }
- );
-
- const pauseIamButton = renderButtonView(
- 'Pause IAM',
- () => {
- OneSignal.InAppMessages.setPaused(true);
- loggingFunction('IAM Paused: true');
- }
- );
-
- const unPauseIamButton = renderButtonView(
- 'Unpause IAM',
- () => {
- OneSignal.InAppMessages.setPaused(false);
- loggingFunction('IAM Paused: false');
- }
- );
-
- const removeTriggerButton = renderButtonView(
- 'Remove trigger for key',
- () => {
- const key = this.props.inputFieldValue;
- loggingFunction('Removing trigger for key: ', key);
- OneSignal.InAppMessages.removeTrigger(key);
- }
- );
-
- const addTriggerButton = renderButtonView(
- 'Add trigger with key my_trigger',
- () => {
- const triggerValue = this.props.inputFieldValue;
- loggingFunction(`Adding trigger with key 'my_trigger' and value ${triggerValue}`);
- OneSignal.InAppMessages.addTrigger('my_trigger', triggerValue);
- }
- );
-
- const addTriggersButton = renderButtonView(
- 'Add list of test triggers',
- () => {
- loggingFunction('Adding a list of test triggers');
- OneSignal.InAppMessages.addTriggers({
- 'my_trigger_1': 'my_trigger_1_value',
- 'my_trigger_2': 'my_trigger_2_value',
- 'my_trigger_3': 'my_trigger_3_value',
- });
- }
- );
-
- const removeTriggersButton = renderButtonView(
- 'Remove list of test triggers',
- () => {
- loggingFunction('Removing list of test triggers');
- OneSignal.InAppMessages.removeTriggers(['my_trigger_1', 'my_trigger_2', 'my_trigger_3']);
- }
- );
-
- const clearAllTriggersButton = renderButtonView(
- 'Clear all triggers',
- () => {
- const triggerValue = this.props.inputFieldValue;
- loggingFunction(`Clearing all triggers`);
- OneSignal.InAppMessages.clearTriggers();
- }
- );
-
- return [
- getPausedButton,
- pauseIamButton,
- unPauseIamButton,
- addTriggerButton,
- removeTriggerButton,
- addTriggersButton,
- removeTriggersButton,
- clearAllTriggersButton,
- ];
- }
-
- createLocationFields() {
- const {loggingFunction} = this.props;
- const locationShared = renderButtonView(
- 'Is Location Shared',
- async () => {
- const isLocationShared = await OneSignal.Location.isShared();
- loggingFunction(`Application has location shared active: ${isLocationShared}`);
- });
-
- const setLocationShared = renderButtonView(
- 'Share Location',
- () => {
- loggingFunction('Sharing location');
- OneSignal.Location.setShared(true);
-
- }
- );
-
- const setLocationUnshared = renderButtonView(
- 'Unshare Location',
- () => {
- loggingFunction('Unsharing location');
- OneSignal.Location.setShared(false);
- }
- );
-
- const requestPermissionButton = renderButtonView(
- 'Request Location Permission',
- () => {
- loggingFunction('Request Location permission');
- OneSignal.Location.requestPermission();
- }
- );
-
- return [
- locationShared,
- setLocationShared,
- setLocationUnshared,
- requestPermissionButton
- ];
- }
-
- createNotificationFields() {
- const {loggingFunction} = this.props;
-
- const hasPermissionButton = renderButtonView(
- 'Has Notification Permission',
- () => {
- const granted = OneSignal.Notifications.hasPermission();
- loggingFunction(`Has Notification Permission: ${granted}`);
- }
- );
-
- const canRequestPermissionButton = renderButtonView(
- 'Can Request Permission',
- async () => {
- const granted = await OneSignal.Notifications.canRequestPermission();
- loggingFunction(`Can Request Permission: ${granted}`);
- }
- );
-
- const requestPermissionButton = renderButtonView(
- 'Request Permission',
- async () => {
- loggingFunction('Requesting notification permission');
- OneSignal.Notifications.requestPermission(false, granted => {
- loggingFunction(`Notification permission granted ${granted}`);
- });
- }
- );
-
- const clearOneSignalNotificationsButton = renderButtonView(
- 'Clear OneSignal Notifications',
- () => {
- loggingFunction('Clearing all OneSignal Notifications');
- OneSignal.Notifications.clearAll();
- }
- );
-
- return [
- hasPermissionButton,
- canRequestPermissionButton,
- requestPermissionButton,
- clearOneSignalNotificationsButton
- ];
- }
-
- createSessionFields() {
- const {loggingFunction} = this.props;
-
- const sendOutcomeButton = renderButtonView(
- 'Send Outcome With Name',
- () => {
- loggingFunction('Sending outcome: ', this.props.inputFieldValue);
- OneSignal.Session.addOutcome(this.props.inputFieldValue);
- }
- );
-
- const sendUniqueOutcomeButton = renderButtonView(
- 'Send Unique Outcome With Name',
- () => {
- loggingFunction('Sending unique outcome: ', this.props.inputFieldValue);
- OneSignal.Session.addUniqueOutcome(this.props.inputFieldValue);
- }
- );
-
- const sendOutcomeWithValueButton = renderButtonView(
- 'Send "my_outcome" with value',
- () => {
- const value = Number(this.props.inputFieldValue);
- loggingFunction('Sending outcome of name "my_outcome" with value: ', value);
-
- if (Number.isNaN(value)) {
- console.error('Outcome with value should be a number');
- return;
- }
- OneSignal.Session.addOutcomeWithValue('my_outcome', value);
- }
- );
-
- return [sendOutcomeButton, sendUniqueOutcomeButton, sendOutcomeWithValueButton];
- }
-
- createUserFields() {
- const {loggingFunction} = this.props;
-
- const addEmailButton = renderButtonView(
- 'Add Email',
- () => {
- loggingFunction('Attempting to set email: ', this.props.inputFieldValue);
- OneSignal.User.addEmail(this.props.inputFieldValue);
- }
- );
-
- const removeEmailButton = renderButtonView(
- 'Remove Email',
- () => {
- loggingFunction('Attempting to remove email: ', this.props.inputFieldValue);
- OneSignal.User.removeEmail(this.props.inputFieldValue);
- }
- );
-
- const loginButton = renderButtonView(
- 'Login',
- () => {
- loggingFunction('Attempting to login a user: ', this.props.inputFieldValue);
- OneSignal.login(this.props.inputFieldValue);
- }
- )
-
- const logoutButton = renderButtonView(
- 'Logout',
- () => {
- loggingFunction('Attempting to logout a user: ');
- OneSignal.logout();
- }
- )
-
- const sendTagWithKeyButton = renderButtonView(
- 'Send tag with key my_tag',
- async () => {
- loggingFunction('Sending tag with value: ', this.props.inputFieldValue);
- OneSignal.User.addTag('my_tag', this.props.inputFieldValue);
- }
- );
-
- const deleteTagWithKeyButton = renderButtonView(
- 'Delete Tag With Key',
- async () => {
- loggingFunction('Deleting tag with key: ', this.props.inputFieldValue);
- OneSignal.User.removeTag(this.props.inputFieldValue);
- }
- );
-
- const addTagsButton = renderButtonView(
- 'Add list of tags',
- () => {
- loggingFunction('Adding list of tags');
- OneSignal.User.addTags({'my_tag1': 'my_value', 'my_tag2': 'my_value2'});
- }
- );
-
- const removeTagsButton = renderButtonView(
- 'Remove list of tags',
- () => {
- loggingFunction('Removing list of tags');
- OneSignal.User.removeTags(['my_tag1', 'my_tag2']);
- }
- );
-
- const setLanguageButton = renderButtonView(
- 'Set Language',
- () => {
- loggingFunction('Attempting to set language: ', this.props.inputFieldValue);
- OneSignal.User.setLanguage(this.props.inputFieldValue);
- }
- );
-
- const addSmsButton = renderButtonView(
- 'Set SMS Number',
- () => {
- loggingFunction('Attempting to set SMS number: ', this.props.inputFieldValue);
- OneSignal.User.addSms(this.props.inputFieldValue);
- }
- );
-
- const removeSmsButton = renderButtonView(
- 'Logout SMS Number',
- () => {
- loggingFunction('Attempting to remove SMS number: ', this.props.inputFieldValue);
- OneSignal.User.removeSms(this.props.inputFieldValue);
- }
- );
-
- const addAliasButton = renderButtonView(
- 'Add my_alias with value',
- () => {
- loggingFunction('Adding my_alias alias with value: ', this.props.inputFieldValue);
- OneSignal.User.addAlias('my_alias', this.props.inputFieldValue);
- }
- );
-
- const removeAliasButton = renderButtonView(
- 'Remove my_alias',
- () => {
- loggingFunction('Removing my_alias');
- OneSignal.User.removeAlias('my_alias');
- }
- );
-
- const addAliasesButton = renderButtonView(
- 'Add list of test aliases',
- () => {
- loggingFunction('Adding a list of test aliases ');
- OneSignal.User.addAliases({
- 'my_alias_1': 'my_alias_1_id',
- 'my_alias_2': 'my_alias_2_id',
- 'my_alias_3': 'my_alias_3_id',
- });
- }
- );
-
- const removeAliasesButton = renderButtonView(
- 'Remove list of test aliases',
- () => {
- loggingFunction('Removing list of test aliases');
- OneSignal.User.removeAliases(['my_alias_1', 'my_alias_2', 'my_alias_3']);
- }
- );
-
- return [
- loginButton,
- logoutButton,
- addEmailButton,
- removeEmailButton,
- sendTagWithKeyButton,
- deleteTagWithKeyButton,
- addTagsButton,
- removeTagsButton,
- setLanguageButton,
- addSmsButton,
- removeSmsButton,
- addAliasButton,
- removeAliasButton,
- addAliasesButton,
- removeAliasesButton,
- ];
- }
-
- pushSubscriptionFields() {
- const {loggingFunction} = this.props;
-
- const getPushSubscriptionIdButton = renderButtonView(
- 'Get Push Subscription Id',
- async () => {
- const id = await OneSignal.User.PushSubscription.getPushSubscriptionId();
- loggingFunction('Push Subscription Id: ', id);
- }
- );
+ createInAppMessagesFields() {
+ const {loggingFunction} = this.props;
+
+ const getPausedButton = renderButtonView('Get paused', async () => {
+ const paused = await OneSignal.InAppMessages.getPaused();
+ loggingFunction(`Is IAM Paused: ${paused}`);
+ });
+
+ const pauseIamButton = renderButtonView('Pause IAM', () => {
+ OneSignal.InAppMessages.setPaused(true);
+ loggingFunction('IAM Paused: true');
+ });
+
+ const unPauseIamButton = renderButtonView('Unpause IAM', () => {
+ OneSignal.InAppMessages.setPaused(false);
+ loggingFunction('IAM Paused: false');
+ });
+
+ const removeTriggerButton = renderButtonView(
+ 'Remove trigger for key',
+ () => {
+ const key = this.props.inputFieldValue;
+ loggingFunction('Removing trigger for key: ', key);
+ OneSignal.InAppMessages.removeTrigger(key);
+ },
+ );
+
+ const addTriggerButton = renderButtonView(
+ 'Add trigger with key my_trigger',
+ () => {
+ const triggerValue = this.props.inputFieldValue;
+ loggingFunction(
+ `Adding trigger with key 'my_trigger' and value ${triggerValue}`,
+ );
+ OneSignal.InAppMessages.addTrigger('my_trigger', triggerValue);
+ },
+ );
+
+ const addTriggersButton = renderButtonView(
+ 'Add list of test triggers',
+ () => {
+ loggingFunction('Adding a list of test triggers');
+ OneSignal.InAppMessages.addTriggers({
+ my_trigger_1: 'my_trigger_1_value',
+ my_trigger_2: 'my_trigger_2_value',
+ my_trigger_3: 'my_trigger_3_value',
+ });
+ },
+ );
+
+ const removeTriggersButton = renderButtonView(
+ 'Remove list of test triggers',
+ () => {
+ loggingFunction('Removing list of test triggers');
+ OneSignal.InAppMessages.removeTriggers([
+ 'my_trigger_1',
+ 'my_trigger_2',
+ 'my_trigger_3',
+ ]);
+ },
+ );
+
+ const clearAllTriggersButton = renderButtonView(
+ 'Clear all triggers',
+ () => {
+ const triggerValue = this.props.inputFieldValue;
+ loggingFunction(`Clearing all triggers`);
+ OneSignal.InAppMessages.clearTriggers();
+ },
+ );
+
+ return [
+ getPausedButton,
+ pauseIamButton,
+ unPauseIamButton,
+ addTriggerButton,
+ removeTriggerButton,
+ addTriggersButton,
+ removeTriggersButton,
+ clearAllTriggersButton,
+ ];
+ }
- const getPushSubscriptionTokenButton = renderButtonView(
- 'Get Push Subscription Token',
- async () => {
- const token = await OneSignal.User.PushSubscription.getPushSubscriptionToken();
- loggingFunction('Push Subscription Token: ', token);
- }
- );
+ createLocationFields() {
+ const {loggingFunction} = this.props;
+ const locationShared = renderButtonView('Is Location Shared', async () => {
+ const isLocationShared = await OneSignal.Location.isShared();
+ loggingFunction(
+ `Application has location shared active: ${isLocationShared}`,
+ );
+ });
+
+ const setLocationShared = renderButtonView('Share Location', () => {
+ loggingFunction('Sharing location');
+ OneSignal.Location.setShared(true);
+ });
+
+ const setLocationUnshared = renderButtonView('Unshare Location', () => {
+ loggingFunction('Unsharing location');
+ OneSignal.Location.setShared(false);
+ });
+
+ const requestPermissionButton = renderButtonView(
+ 'Request Location Permission',
+ () => {
+ loggingFunction('Request Location permission');
+ OneSignal.Location.requestPermission();
+ },
+ );
+
+ return [
+ locationShared,
+ setLocationShared,
+ setLocationUnshared,
+ requestPermissionButton,
+ ];
+ }
- const getOptedInButton = renderButtonView(
- 'Is Opted In',
- async () => {
- const optedIn = await OneSignal.User.PushSubscription.getOptedIn();
- loggingFunction('Subscribed for the push notifications: ', optedIn);
- }
- );
+ createNotificationFields() {
+ const {loggingFunction} = this.props;
+
+ const hasPermissionButton = renderButtonView(
+ 'Has Notification Permission',
+ () => {
+ const granted = OneSignal.Notifications.hasPermission();
+ loggingFunction(`Has Notification Permission: ${granted}`);
+ },
+ );
+
+ const canRequestPermissionButton = renderButtonView(
+ 'Can Request Permission',
+ async () => {
+ const granted = await OneSignal.Notifications.canRequestPermission();
+ loggingFunction(`Can Request Permission: ${granted}`);
+ },
+ );
+
+ const requestPermissionButton = renderButtonView(
+ 'Request Permission',
+ async () => {
+ loggingFunction('Requesting notification permission');
+ OneSignal.Notifications.requestPermission(false, (granted) => {
+ loggingFunction(`Notification permission granted ${granted}`);
+ });
+ },
+ );
+
+ const clearOneSignalNotificationsButton = renderButtonView(
+ 'Clear OneSignal Notifications',
+ () => {
+ loggingFunction('Clearing all OneSignal Notifications');
+ OneSignal.Notifications.clearAll();
+ },
+ );
+
+ return [
+ hasPermissionButton,
+ canRequestPermissionButton,
+ requestPermissionButton,
+ clearOneSignalNotificationsButton,
+ ];
+ }
- const optInButton = renderButtonView(
- 'Opt In',
- () => {
- loggingFunction('Subscribing for the push notifications');
- OneSignal.User.PushSubscription.optIn();
- }
- );
+ createSessionFields() {
+ const {loggingFunction} = this.props;
+
+ const sendOutcomeButton = renderButtonView('Send Outcome With Name', () => {
+ loggingFunction('Sending outcome: ', this.props.inputFieldValue);
+ OneSignal.Session.addOutcome(this.props.inputFieldValue);
+ });
+
+ const sendUniqueOutcomeButton = renderButtonView(
+ 'Send Unique Outcome With Name',
+ () => {
+ loggingFunction('Sending unique outcome: ', this.props.inputFieldValue);
+ OneSignal.Session.addUniqueOutcome(this.props.inputFieldValue);
+ },
+ );
+
+ const sendOutcomeWithValueButton = renderButtonView(
+ 'Send "my_outcome" with value',
+ () => {
+ const value = Number(this.props.inputFieldValue);
+ loggingFunction(
+ 'Sending outcome of name "my_outcome" with value: ',
+ value,
+ );
+
+ if (Number.isNaN(value)) {
+ console.error('Outcome with value should be a number');
+ return;
+ }
+ OneSignal.Session.addOutcomeWithValue('my_outcome', value);
+ },
+ );
+
+ return [
+ sendOutcomeButton,
+ sendUniqueOutcomeButton,
+ sendOutcomeWithValueButton,
+ ];
+ }
- const optOutButton = renderButtonView(
- 'Opt Out',
- () => {
- loggingFunction('Unsubscribing from the push notifications');
- OneSignal.User.PushSubscription.optOut();
- }
- );
+ createUserFields() {
+ const {loggingFunction} = this.props;
+
+ const addEmailButton = renderButtonView('Add Email', () => {
+ loggingFunction('Attempting to set email: ', this.props.inputFieldValue);
+ OneSignal.User.addEmail(this.props.inputFieldValue);
+ });
+
+ const removeEmailButton = renderButtonView('Remove Email', () => {
+ loggingFunction(
+ 'Attempting to remove email: ',
+ this.props.inputFieldValue,
+ );
+ OneSignal.User.removeEmail(this.props.inputFieldValue);
+ });
+
+ const loginButton = renderButtonView('Login', () => {
+ loggingFunction(
+ 'Attempting to login a user: ',
+ this.props.inputFieldValue,
+ );
+ OneSignal.login(this.props.inputFieldValue);
+ });
+
+ const logoutButton = renderButtonView('Logout', () => {
+ loggingFunction('Attempting to logout a user: ');
+ OneSignal.logout();
+ });
+
+ const sendTagWithKeyButton = renderButtonView(
+ 'Send tag with key my_tag',
+ async () => {
+ loggingFunction('Sending tag with value: ', this.props.inputFieldValue);
+ OneSignal.User.addTag('my_tag', this.props.inputFieldValue);
+ },
+ );
+
+ const deleteTagWithKeyButton = renderButtonView(
+ 'Delete Tag With Key',
+ async () => {
+ loggingFunction('Deleting tag with key: ', this.props.inputFieldValue);
+ OneSignal.User.removeTag(this.props.inputFieldValue);
+ },
+ );
+
+ const addTagsButton = renderButtonView('Add list of tags', () => {
+ loggingFunction('Adding list of tags');
+ OneSignal.User.addTags({my_tag1: 'my_value', my_tag2: 'my_value2'});
+ });
+
+ const removeTagsButton = renderButtonView('Remove list of tags', () => {
+ loggingFunction('Removing list of tags');
+ OneSignal.User.removeTags(['my_tag1', 'my_tag2']);
+ });
+
+ const setLanguageButton = renderButtonView('Set Language', () => {
+ loggingFunction(
+ 'Attempting to set language: ',
+ this.props.inputFieldValue,
+ );
+ OneSignal.User.setLanguage(this.props.inputFieldValue);
+ });
+
+ const addSmsButton = renderButtonView('Set SMS Number', () => {
+ loggingFunction(
+ 'Attempting to set SMS number: ',
+ this.props.inputFieldValue,
+ );
+ OneSignal.User.addSms(this.props.inputFieldValue);
+ });
+
+ const removeSmsButton = renderButtonView('Logout SMS Number', () => {
+ loggingFunction(
+ 'Attempting to remove SMS number: ',
+ this.props.inputFieldValue,
+ );
+ OneSignal.User.removeSms(this.props.inputFieldValue);
+ });
+
+ const addAliasButton = renderButtonView('Add my_alias with value', () => {
+ loggingFunction(
+ 'Adding my_alias alias with value: ',
+ this.props.inputFieldValue,
+ );
+ OneSignal.User.addAlias('my_alias', this.props.inputFieldValue);
+ });
+
+ const removeAliasButton = renderButtonView('Remove my_alias', () => {
+ loggingFunction('Removing my_alias');
+ OneSignal.User.removeAlias('my_alias');
+ });
+
+ const addAliasesButton = renderButtonView(
+ 'Add list of test aliases',
+ () => {
+ loggingFunction('Adding a list of test aliases ');
+ OneSignal.User.addAliases({
+ my_alias_1: 'my_alias_1_id',
+ my_alias_2: 'my_alias_2_id',
+ my_alias_3: 'my_alias_3_id',
+ });
+ },
+ );
+
+ const removeAliasesButton = renderButtonView(
+ 'Remove list of test aliases',
+ () => {
+ loggingFunction('Removing list of test aliases');
+ OneSignal.User.removeAliases([
+ 'my_alias_1',
+ 'my_alias_2',
+ 'my_alias_3',
+ ]);
+ },
+ );
+
+ return [
+ loginButton,
+ logoutButton,
+ addEmailButton,
+ removeEmailButton,
+ sendTagWithKeyButton,
+ deleteTagWithKeyButton,
+ addTagsButton,
+ removeTagsButton,
+ setLanguageButton,
+ addSmsButton,
+ removeSmsButton,
+ addAliasButton,
+ removeAliasButton,
+ addAliasesButton,
+ removeAliasesButton,
+ ];
+ }
- return [
- getPushSubscriptionIdButton,
- getPushSubscriptionTokenButton,
- getOptedInButton,
- optInButton,
- optOutButton,
- ];
- }
-
- privacyConsentFields() {
- const {loggingFunction} = this.props;
-
- const setPrivacyConsentGivenTrueButton = renderButtonView(
- 'Set Privacy Consent to true',
- async () => {
- await OneSignal.setConsentGiven(true);
- loggingFunction('Privacy Consent set to true');
- }
- );
+ pushSubscriptionFields() {
+ const {loggingFunction} = this.props;
+
+ const getPushSubscriptionIdButton = renderButtonView(
+ 'Get Push Subscription Id',
+ async () => {
+ const id =
+ await OneSignal.User.PushSubscription.getPushSubscriptionId();
+ loggingFunction('Push Subscription Id: ', id);
+ },
+ );
+
+ const getPushSubscriptionTokenButton = renderButtonView(
+ 'Get Push Subscription Token',
+ async () => {
+ const token =
+ await OneSignal.User.PushSubscription.getPushSubscriptionToken();
+ loggingFunction('Push Subscription Token: ', token);
+ },
+ );
+
+ const getOptedInButton = renderButtonView('Is Opted In', async () => {
+ const optedIn = await OneSignal.User.PushSubscription.getOptedIn();
+ loggingFunction('Subscribed for the push notifications: ', optedIn);
+ });
+
+ const optInButton = renderButtonView('Opt In', () => {
+ loggingFunction('Subscribing for the push notifications');
+ OneSignal.User.PushSubscription.optIn();
+ });
+
+ const optOutButton = renderButtonView('Opt Out', () => {
+ loggingFunction('Unsubscribing from the push notifications');
+ OneSignal.User.PushSubscription.optOut();
+ });
+
+ return [
+ getPushSubscriptionIdButton,
+ getPushSubscriptionTokenButton,
+ getOptedInButton,
+ optInButton,
+ optOutButton,
+ ];
+ }
- const setPrivacyConsentGivenFalseButton = renderButtonView(
- 'Set Privacy Consent to false',
- async () => {
- await OneSignal.setConsentGiven(false);
- loggingFunction('Privacy Consent set to false');
- }
- );
+ privacyConsentFields() {
+ const {loggingFunction} = this.props;
+
+ const setPrivacyConsentGivenTrueButton = renderButtonView(
+ 'Set Privacy Consent to true',
+ async () => {
+ await OneSignal.setConsentGiven(true);
+ loggingFunction('Privacy Consent set to true');
+ },
+ );
+
+ const setPrivacyConsentGivenFalseButton = renderButtonView(
+ 'Set Privacy Consent to false',
+ async () => {
+ await OneSignal.setConsentGiven(false);
+ loggingFunction('Privacy Consent set to false');
+ },
+ );
+
+ const setPrivacyConsentRequiredTrueButton = renderButtonView(
+ 'Set Requiers Privacy Consent to true',
+ async () => {
+ await OneSignal.setConsentRequired(true);
+ loggingFunction('Requires Privacy Consent set to true');
+ },
+ );
+
+ const setPrivacyConsentRequiredFalseButton = renderButtonView(
+ 'Set Requiers Privacy Consent to false',
+ async () => {
+ await OneSignal.setConsentRequired(false);
+ loggingFunction('Requires Privacy Consent set to false');
+ },
+ );
+
+ return [
+ setPrivacyConsentGivenTrueButton,
+ setPrivacyConsentGivenFalseButton,
+ setPrivacyConsentRequiredTrueButton,
+ setPrivacyConsentRequiredFalseButton,
+ ];
+ }
- const setPrivacyConsentRequiredTrueButton = renderButtonView(
- 'Set Requiers Privacy Consent to true',
- async () => {
- await OneSignal.setConsentRequired(true);
- loggingFunction('Requires Privacy Consent set to true');
- }
- );
-
- const setPrivacyConsentRequiredFalseButton = renderButtonView(
- 'Set Requiers Privacy Consent to false',
- async () => {
- await OneSignal.setConsentRequired(false);
- loggingFunction('Requires Privacy Consent set to false');
- }
- );
-
- return [
- setPrivacyConsentGivenTrueButton,
- setPrivacyConsentGivenFalseButton,
- setPrivacyConsentRequiredTrueButton,
- setPrivacyConsentRequiredFalseButton,
- ];
- }
-
- render() {
- return (
-
-
- InAppMessages
-
- { this.createInAppMessagesFields() }
-
-
- Location
-
- { this.createLocationFields() }
-
-
- Notifications
-
- { this.createNotificationFields() }
-
-
- Session
-
- { this.createSessionFields() }
-
-
- User
-
- { this.createUserFields() }
-
-
- Push Subscription
-
- { this.pushSubscriptionFields() }
-
-
- Privacy Consent
-
- { this.privacyConsentFields() }
-
- );
- }
-};
+ render() {
+ return (
+
+
+ InAppMessages
+
+ {this.createInAppMessagesFields()}
+
+
+ Location
+
+ {this.createLocationFields()}
+
+
+ Notifications
+
+ {this.createNotificationFields()}
+
+
+ Session
+
+ {this.createSessionFields()}
+
+
+ User
+
+ {this.createUserFields()}
+
+
+ Push Subscription
+
+ {this.pushSubscriptionFields()}
+
+
+ Privacy Consent
+
+ {this.privacyConsentFields()}
+
+ );
+ }
+}
const styles = StyleSheet.create({
greeting: {
color: '#999',
- fontWeight: 'bold'
- }
+ fontWeight: 'bold',
+ },
});
export default OSButtons;
diff --git a/examples/RNOneSignalTS/src/OSConsole.tsx b/examples/RNOneSignalTS/src/OSConsole.tsx
index 8a99aa07..05f2a905 100644
--- a/examples/RNOneSignalTS/src/OSConsole.tsx
+++ b/examples/RNOneSignalTS/src/OSConsole.tsx
@@ -10,19 +10,21 @@
import React from 'react';
import {
- SafeAreaView, StyleSheet, ScrollView, View, Text, Platform,
+ SafeAreaView,
+ StyleSheet,
+ ScrollView,
+ View,
+ Text,
+ Platform,
} from 'react-native';
-import {
- Colors
-} from 'react-native/Libraries/NewAppScreen';
+import {Colors} from 'react-native/Libraries/NewAppScreen';
export interface Props {
value: string;
}
-export interface State {
-}
+export interface State {}
class OSConsole extends React.Component {
constructor(props: Props) {
@@ -31,36 +33,60 @@ class OSConsole extends React.Component {
scrollToEnd = () => {
this.scrollView.scrollToEnd({animated: true});
- }
+ };
render() {
- return (
- {
- this.scrollView = scrollView
- }}
- onContentSizeChange={() => this.scrollToEnd()}>
-
- {this.props.value}
-
-
- );
+ return (
+
+ {
+ this.scrollView = scrollView;
+ }}
+ onContentSizeChange={() => this.scrollToEnd()}
+ >
+
+
+ {this.props.value}
+
+
+
+
+ );
}
}
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
- }, body: {
- backgroundColor: 'grey', flex: 1, flexGrow: 1, flexDirection: 'row',
- }, console: {
- flexWrap: 'wrap', padding: 10, flexDirection: 'row',
- }, textIOS: {
- fontFamily: 'Courier', flex: 1, flexWrap: 'wrap', fontSize: 10,
- }, textAndroid: {
- flex: 1, flexWrap: 'wrap', fontSize: 10,
- }
+ },
+ body: {
+ backgroundColor: 'grey',
+ flex: 1,
+ flexGrow: 1,
+ flexDirection: 'row',
+ },
+ console: {
+ flexWrap: 'wrap',
+ padding: 10,
+ flexDirection: 'row',
+ },
+ textIOS: {
+ fontFamily: 'Courier',
+ flex: 1,
+ flexWrap: 'wrap',
+ fontSize: 10,
+ },
+ textAndroid: {
+ flex: 1,
+ flexWrap: 'wrap',
+ fontSize: 10,
+ },
});
export default OSConsole;
diff --git a/examples/RNOneSignalTS/src/OSDemo.tsx b/examples/RNOneSignalTS/src/OSDemo.tsx
index bd339f52..e77b998c 100644
--- a/examples/RNOneSignalTS/src/OSDemo.tsx
+++ b/examples/RNOneSignalTS/src/OSDemo.tsx
@@ -4,7 +4,7 @@ import {Alert, StyleSheet, View, ScrollView, SafeAreaView} from 'react-native';
import OSButtons from './OSButtons';
import OSConsole from './OSConsole';
import {renderButtonView} from './Helpers';
-import {TextInput, Text} from "@react-native-material/core";
+import {TextInput, Text} from '@react-native-material/core';
const APP_ID = '77e32082-ea27-42e3-a898-c72e141824ef';
@@ -33,7 +33,8 @@ class OSDemo extends React.Component {
OneSignal.initialize(APP_ID);
OneSignal.Debug.setLogLevel(6);
- OneSignal.Notifications.addEventListener('foregroundWillDisplay',
+ OneSignal.Notifications.addEventListener(
+ 'foregroundWillDisplay',
(event) => {
this.OSLog('OneSignal: notification will show in foreground:', event);
let notif = event.getNotification();
@@ -53,9 +54,14 @@ class OSDemo extends React.Component {
},
};
- Alert.alert('Display notification?', notif.title, [cancelButton, completeButton], {
- cancelable: true,
- });
+ Alert.alert(
+ 'Display notification?',
+ notif.title,
+ [cancelButton, completeButton],
+ {
+ cancelable: true,
+ },
+ );
},
);
@@ -63,23 +69,23 @@ class OSDemo extends React.Component {
this.OSLog('OneSignal: notification clicked:', event);
});
- OneSignal.InAppMessages.addEventListener('click', (event) =>{
+ OneSignal.InAppMessages.addEventListener('click', (event) => {
this.OSLog('OneSignal IAM clicked:', event);
});
- OneSignal.InAppMessages.addEventListener('willDisplay', (event) =>{
+ OneSignal.InAppMessages.addEventListener('willDisplay', (event) => {
this.OSLog('OneSignal: will display IAM: ', event);
});
- OneSignal.InAppMessages.addEventListener('didDisplay', (event) =>{
+ OneSignal.InAppMessages.addEventListener('didDisplay', (event) => {
this.OSLog('OneSignal: did display IAM: ', event);
});
- OneSignal.InAppMessages.addEventListener('willDismiss', (event) =>{
+ OneSignal.InAppMessages.addEventListener('willDismiss', (event) => {
this.OSLog('OneSignal: will dismiss IAM: ', event);
});
- OneSignal.InAppMessages.addEventListener('didDismiss', (event) =>{
+ OneSignal.InAppMessages.addEventListener('didDismiss', (event) => {
this.OSLog('OneSignal: did dismiss IAM: ', event);
});
@@ -135,7 +141,7 @@ class OSDemo extends React.Component {
/>
-
@@ -155,10 +161,10 @@ const styles = StyleSheet.create({
backgroundColor: '#fff',
},
header: {
- flex: .5,
+ flex: 0.5,
},
scrollView: {
- flex: .5,
+ flex: 0.5,
},
title: {
fontSize: 40,
diff --git a/examples/RNOneSignalTS/tsconfig.json b/examples/RNOneSignalTS/tsconfig.json
index 5c9b27a9..760dc8c4 100644
--- a/examples/RNOneSignalTS/tsconfig.json
+++ b/examples/RNOneSignalTS/tsconfig.json
@@ -1,27 +1,28 @@
-
{
"compilerOptions": {
/* Basic Options */
- "target": "esnext", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
- "module": "es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
- "lib": ["es6"], /* Specify library files to be included in the compilation. */
- "allowJs": true, /* Allow javascript files to be compiled. */
+ "target": "esnext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
+ "module": "es2015" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
+ "lib": [
+ "es6"
+ ] /* Specify library files to be included in the compilation. */,
+ "allowJs": true /* Allow javascript files to be compiled. */,
// "checkJs": true, /* Report errors in .js files. */
- "jsx": "react-native", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
+ "jsx": "react-native" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */,
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "removeComments": true, /* Do not emit comments to output. */
- "noEmit": true, /* Do not emit outputs. */
+ "noEmit": true /* Do not emit outputs. */,
// "incremental": true, /* Enable incremental compilation */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
- "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
+ "isolatedModules": true /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */,
/* Strict Type-Checking Options */
- "strict": true, /* Enable all strict type-checking options. */
+ "strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
@@ -36,14 +37,14 @@
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
- "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
+ "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
- "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
- "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
+ "allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,
+ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
@@ -57,6 +58,9 @@
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
},
"exclude": [
- "node_modules", "babel.config.js", "metro.config.js", "jest.config.js"
+ "node_modules",
+ "babel.config.js",
+ "metro.config.js",
+ "jest.config.js"
]
}
diff --git a/jest.config.js b/jest.config.js
index 34037a99..38d21a56 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -1,16 +1,8 @@
module.exports = {
- preset: "react-native",
- moduleDirectories: ["node_modules","src"],
- modulePathIgnorePatterns: ["examples", "dist"],
- collectCoverage: true,
- collectCoverageFrom: ["src/**/*"],
- moduleFileExtensions: [
- "ts",
- "tsx",
- "js",
- "jsx",
- "json",
- "node"
- ]
-}
-
+ preset: 'react-native',
+ moduleDirectories: ['node_modules', 'src'],
+ modulePathIgnorePatterns: ['examples', 'dist'],
+ collectCoverage: true,
+ collectCoverageFrom: ['src/**/*'],
+ moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
+};
diff --git a/src/index.ts b/src/index.ts
index f74995ef..c903a02e 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -13,11 +13,15 @@ import {
PERMISSION_CHANGED,
SUBSCRIPTION_CHANGED,
} from './events/events';
-import { NotificationEventName,
+import {
+ NotificationEventName,
NotificationEventTypeMap,
- NotificationClickedEvent} from './models/NotificationEvents';
-import { PushSubscription,
- OSNotificationPermission } from './models/Subscription';
+ NotificationClickedEvent,
+} from './models/NotificationEvents';
+import {
+ PushSubscription,
+ OSNotificationPermission,
+} from './models/Subscription';
import NotificationWillDisplayEvent from './events/NotificationWillDisplayEvent';
import { OutcomeEvent } from './models/Outcomes';
import {
@@ -25,9 +29,9 @@ import {
InAppMessageEventTypeMap,
InAppMessageEventName,
InAppMessageClickEvent,
- InAppMessageWillDisplayEvent,
- InAppMessageDidDisplayEvent,
- InAppMessageWillDismissEvent,
+ InAppMessageWillDisplayEvent,
+ InAppMessageDidDisplayEvent,
+ InAppMessageWillDismissEvent,
InAppMessageDidDismissEvent,
} from './models/InAppMessage';
import { isValidCallback, isNativeModuleLoaded } from './helpers';
@@ -158,9 +162,9 @@ export namespace OneSignal {
}
export namespace LiveActivities {
- /**
- * Associates a temporary push token with an Activity ID on the OneSignal server.
- */
+ /**
+ * Associates a temporary push token with an Activity ID on the OneSignal server.
+ */
export function enter(
activityId: string,
token: string,
@@ -198,9 +202,7 @@ export namespace OneSignal {
export namespace User {
export namespace PushSubscription {
/** Add a callback that fires when the OneSignal subscription state changes. */
- export function addObserver(
- handler: (event: PushSubscription) => void,
- ) {
+ export function addObserver(handler: (event: PushSubscription) => void) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
isValidCallback(handler);
@@ -396,9 +398,13 @@ export namespace OneSignal {
}
export namespace Notifications {
- export const _notificationClickedListeners: ((action: NotificationClickedEvent) => void)[] = [];
- export const _notificationWillDisplayListeners: ((notification: NotificationWillDisplayEvent) => void)[] = [];
-
+ export const _notificationClickedListeners: ((
+ action: NotificationClickedEvent,
+ ) => void)[] = [];
+ export const _notificationWillDisplayListeners: ((
+ notification: NotificationWillDisplayEvent,
+ ) => void)[] = [];
+
/**
* Whether this app has push notification permission. Returns true if the user has accepted permissions,
* or if the app has ephemeral or provisional permission.
@@ -478,10 +484,10 @@ export namespace OneSignal {
/** iOS Only.
* Returns the enum for the native permission of the device. It will be one of:
- * OSNotificationPermissionNotDetermined,
- * OSNotificationPermissionDenied,
- * OSNotificationPermissionAuthorized,
- * OSNotificationPermissionProvisional - only available in iOS 12,
+ * OSNotificationPermissionNotDetermined,
+ * OSNotificationPermissionDenied,
+ * OSNotificationPermissionAuthorized,
+ * OSNotificationPermissionProvisional - only available in iOS 12,
* OSNotificationPermissionEphemeral - only available in iOS 14
* */
export function permissionNative() {
@@ -490,43 +496,59 @@ export namespace OneSignal {
if (Platform.OS === 'ios') {
return RNOneSignal.permissionNative();
} else {
- return notificationPermission ? OSNotificationPermission.Authorized : OSNotificationPermission.Denied;
+ return notificationPermission
+ ? OSNotificationPermission.Authorized
+ : OSNotificationPermission.Denied;
}
}
/**
* Add listeners for notification click and/or lifecycle events. */
- export function addEventListener(event: K, listener: (event: NotificationEventTypeMap[K]) => void): void {
+ export function addEventListener(
+ event: K,
+ listener: (event: NotificationEventTypeMap[K]) => void,
+ ): void {
if (!isNativeModuleLoaded(RNOneSignal)) return;
isValidCallback(listener);
- if (event === "click") {
- _notificationClickedListeners.push(listener as (event: NotificationClickedEvent) => void);
+ if (event === 'click') {
+ _notificationClickedListeners.push(
+ listener as (event: NotificationClickedEvent) => void,
+ );
RNOneSignal.addNotificationClickListener();
eventManager.setEventHandler(
NOTIFICATION_CLICKED,
- listener as (event: NotificationClickedEvent) => void
+ listener as (event: NotificationClickedEvent) => void,
+ );
+ } else if (event === 'foregroundWillDisplay') {
+ _notificationWillDisplayListeners.push(
+ listener as (event: NotificationWillDisplayEvent) => void,
);
- } else if (event === "foregroundWillDisplay") {
- _notificationWillDisplayListeners.push(listener as (event: NotificationWillDisplayEvent) => void);
RNOneSignal.addNotificationForegroundLifecycleListener();
eventManager.setEventHandler(
NOTIFICATION_WILL_DISPLAY,
- listener as (event: NotificationWillDisplayEvent) => void
+ listener as (event: NotificationWillDisplayEvent) => void,
);
}
}
/**
* Remove listeners for notification click and/or lifecycle events. */
- export function removeEventListener(event: K, listener: (obj: NotificationEventTypeMap[K]) => void): void {
- if (event === "click") {
- let index = _notificationClickedListeners.indexOf(listener as (event: NotificationClickedEvent) => void);
+ export function removeEventListener(
+ event: K,
+ listener: (obj: NotificationEventTypeMap[K]) => void,
+ ): void {
+ if (event === 'click') {
+ let index = _notificationClickedListeners.indexOf(
+ listener as (event: NotificationClickedEvent) => void,
+ );
if (index !== -1) {
_notificationClickedListeners.splice(index, 1);
}
- } else if (event === "foregroundWillDisplay") {
- let index = _notificationWillDisplayListeners.indexOf(listener as (event: NotificationWillDisplayEvent) => void);
+ } else if (event === 'foregroundWillDisplay') {
+ let index = _notificationWillDisplayListeners.indexOf(
+ listener as (event: NotificationWillDisplayEvent) => void,
+ );
if (index !== -1) {
_notificationWillDisplayListeners.splice(index, 1);
}
@@ -580,63 +602,81 @@ export namespace OneSignal {
}
export namespace InAppMessages {
- export const _inAppMessageClickListeners: ((action: InAppMessageClickEvent) => void)[] = [];
- export const _willDisplayInAppMessageListeners: ((event: InAppMessageWillDisplayEvent) => void) [] = [];
- export const _didDisplayInAppMessageListeners: ((event: InAppMessageDidDisplayEvent) => void) [] = [];
- export const _willDismissInAppMessageListeners: ((event: InAppMessageWillDismissEvent) => void) [] = [];
- export const _didDismissInAppMessageListeners: ((event: InAppMessageDidDismissEvent) => void) [] = [];
+ export const _inAppMessageClickListeners: ((
+ action: InAppMessageClickEvent,
+ ) => void)[] = [];
+ export const _willDisplayInAppMessageListeners: ((
+ event: InAppMessageWillDisplayEvent,
+ ) => void)[] = [];
+ export const _didDisplayInAppMessageListeners: ((
+ event: InAppMessageDidDisplayEvent,
+ ) => void)[] = [];
+ export const _willDismissInAppMessageListeners: ((
+ event: InAppMessageWillDismissEvent,
+ ) => void)[] = [];
+ export const _didDismissInAppMessageListeners: ((
+ event: InAppMessageDidDismissEvent,
+ ) => void)[] = [];
/**
* Add listeners for notification click and/or lifecycle events.
*/
- export function addEventListener(event: K, listener: (event: InAppMessageEventTypeMap[K]) => void): void {
+ export function addEventListener(
+ event: K,
+ listener: (event: InAppMessageEventTypeMap[K]) => void,
+ ): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
- if (event === "click") {
+ if (event === 'click') {
isValidCallback(listener);
- _inAppMessageClickListeners.push(listener as (event: InAppMessageClickEvent) => void);
+ _inAppMessageClickListeners.push(
+ listener as (event: InAppMessageClickEvent) => void,
+ );
RNOneSignal.addInAppMessageClickListener();
eventManager.setEventHandler(
IN_APP_MESSAGE_CLICKED,
- listener as (event: InAppMessageClickEvent) => void
+ listener as (event: InAppMessageClickEvent) => void,
);
- }
- else{
- if (event === "willDisplay") {
+ } else {
+ if (event === 'willDisplay') {
isValidCallback(listener);
- _willDisplayInAppMessageListeners.push(listener as (event: InAppMessageWillDisplayEvent) => void);
+ _willDisplayInAppMessageListeners.push(
+ listener as (event: InAppMessageWillDisplayEvent) => void,
+ );
eventManager.setEventHandler(
IN_APP_MESSAGE_WILL_DISPLAY,
- listener as (event: InAppMessageWillDisplayEvent) => void
+ listener as (event: InAppMessageWillDisplayEvent) => void,
);
- }
- else if (event === "didDisplay") {
+ } else if (event === 'didDisplay') {
isValidCallback(listener);
- _didDisplayInAppMessageListeners.push(listener as (event: InAppMessageDidDisplayEvent) => void);
+ _didDisplayInAppMessageListeners.push(
+ listener as (event: InAppMessageDidDisplayEvent) => void,
+ );
eventManager.setEventHandler(
IN_APP_MESSAGE_DID_DISPLAY,
- listener as (event: InAppMessageDidDisplayEvent) => void
+ listener as (event: InAppMessageDidDisplayEvent) => void,
);
- }
- else if (event === "willDismiss"){
+ } else if (event === 'willDismiss') {
isValidCallback(listener);
- _willDismissInAppMessageListeners.push(listener as (event: InAppMessageWillDismissEvent) => void);
+ _willDismissInAppMessageListeners.push(
+ listener as (event: InAppMessageWillDismissEvent) => void,
+ );
eventManager.setEventHandler(
IN_APP_MESSAGE_WILL_DISMISS,
- listener as (event: InAppMessageWillDismissEvent) => void
+ listener as (event: InAppMessageWillDismissEvent) => void,
);
- }
- else if (event === "didDismiss"){
+ } else if (event === 'didDismiss') {
isValidCallback(listener);
- _didDismissInAppMessageListeners.push(listener as (event: InAppMessageDidDismissEvent) => void);
+ _didDismissInAppMessageListeners.push(
+ listener as (event: InAppMessageDidDismissEvent) => void,
+ );
eventManager.setEventHandler(
IN_APP_MESSAGE_DID_DISMISS,
- listener as (event: InAppMessageDidDismissEvent) => void
+ listener as (event: InAppMessageDidDismissEvent) => void,
);
- }
- else {
+ } else {
return;
}
RNOneSignal.addInAppMessagesLifecycleListener();
@@ -646,36 +686,47 @@ export namespace OneSignal {
/**
* Remove listeners for In-App Message click and/or lifecycle events.
*/
- export function removeEventListener(event: K, listener: (obj: InAppMessageEventTypeMap[K]) => void): void {
- if (event === "click") {
+ export function removeEventListener(
+ event: K,
+ listener: (obj: InAppMessageEventTypeMap[K]) => void,
+ ): void {
+ if (event === 'click') {
const index = _inAppMessageClickListeners.indexOf(listener);
if (index !== -1) {
- _inAppMessageClickListeners.splice(index, 1);
+ _inAppMessageClickListeners.splice(index, 1);
}
- } else {
- if (event === "willDisplay") {
- let index = _willDisplayInAppMessageListeners.indexOf(listener as (event: InAppMessageWillDisplayEvent) => void);
- if (index !== -1) {
- _willDisplayInAppMessageListeners.splice(index, 1);
- }
- } else if (event === "didDisplay") {
- let index = _didDisplayInAppMessageListeners.indexOf(listener as (event: InAppMessageDidDisplayEvent) => void);
- if (index !== -1) {
- _willDisplayInAppMessageListeners.splice(index, 1);
- }
- } else if (event === "willDismiss") {
- let index = _willDismissInAppMessageListeners.indexOf(listener as (event: InAppMessageWillDismissEvent) => void);
- if (index !== -1) {
- _willDismissInAppMessageListeners.splice(index, 1);
- }
- } else if (event === "didDismiss") {
- let index = _didDismissInAppMessageListeners.indexOf(listener as (event: InAppMessageDidDismissEvent) => void);
- if (index !== -1) {
- _didDismissInAppMessageListeners.splice(index, 1);
- }
- } else {
- return;
+ } else {
+ if (event === 'willDisplay') {
+ let index = _willDisplayInAppMessageListeners.indexOf(
+ listener as (event: InAppMessageWillDisplayEvent) => void,
+ );
+ if (index !== -1) {
+ _willDisplayInAppMessageListeners.splice(index, 1);
}
+ } else if (event === 'didDisplay') {
+ let index = _didDisplayInAppMessageListeners.indexOf(
+ listener as (event: InAppMessageDidDisplayEvent) => void,
+ );
+ if (index !== -1) {
+ _willDisplayInAppMessageListeners.splice(index, 1);
+ }
+ } else if (event === 'willDismiss') {
+ let index = _willDismissInAppMessageListeners.indexOf(
+ listener as (event: InAppMessageWillDismissEvent) => void,
+ );
+ if (index !== -1) {
+ _willDismissInAppMessageListeners.splice(index, 1);
+ }
+ } else if (event === 'didDismiss') {
+ let index = _didDismissInAppMessageListeners.indexOf(
+ listener as (event: InAppMessageDidDismissEvent) => void,
+ );
+ if (index !== -1) {
+ _didDismissInAppMessageListeners.splice(index, 1);
+ }
+ } else {
+ return;
+ }
}
}
@@ -700,9 +751,7 @@ export namespace OneSignal {
* Add multiple triggers for the current user. Triggers are currently explicitly used to determine whether a specific IAM should
* be displayed to the user.
*/
- export function addTriggers(triggers: {
- [key: string]: string;
- }) {
+ export function addTriggers(triggers: { [key: string]: string }) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
let keys = Object.keys(triggers);
@@ -818,9 +867,9 @@ export {
NotificationClickedEvent,
InAppMessage,
InAppMessageClickEvent,
- InAppMessageWillDisplayEvent,
- InAppMessageDidDisplayEvent,
- InAppMessageWillDismissEvent,
+ InAppMessageWillDisplayEvent,
+ InAppMessageDidDisplayEvent,
+ InAppMessageWillDismissEvent,
InAppMessageDidDismissEvent,
OutcomeEvent,
};
diff --git a/src/models/InAppMessage.ts b/src/models/InAppMessage.ts
index ff640c64..36b5007c 100644
--- a/src/models/InAppMessage.ts
+++ b/src/models/InAppMessage.ts
@@ -1,4 +1,9 @@
-export type InAppMessageEventName = "click" | "willDisplay" | "didDisplay" | "willDismiss" | "didDismiss";
+export type InAppMessageEventName =
+ | 'click'
+ | 'willDisplay'
+ | 'didDisplay'
+ | 'willDismiss'
+ | 'didDismiss';
export type InAppMessageEventTypeMap = {
click: InAppMessageClickEvent;
@@ -13,8 +18,8 @@ export interface InAppMessage {
}
export interface InAppMessageClickEvent {
- message : InAppMessage
- result : InAppMessageClickResult
+ message: InAppMessage;
+ result: InAppMessageClickResult;
}
export interface InAppMessageClickResult {
@@ -25,17 +30,17 @@ export interface InAppMessageClickResult {
}
export interface InAppMessageWillDisplayEvent {
- message : InAppMessage
+ message: InAppMessage;
}
export interface InAppMessageDidDisplayEvent {
- message : InAppMessage
+ message: InAppMessage;
}
export interface InAppMessageWillDismissEvent {
- message : InAppMessage
+ message: InAppMessage;
}
export interface InAppMessageDidDismissEvent {
- message : InAppMessage
+ message: InAppMessage;
}
diff --git a/src/models/NotificationEvents.ts b/src/models/NotificationEvents.ts
index d1e72cb3..9829c726 100644
--- a/src/models/NotificationEvents.ts
+++ b/src/models/NotificationEvents.ts
@@ -1,7 +1,7 @@
import OSNotification from '../OSNotification';
import NotificationWillDisplayEvent from '../events/NotificationWillDisplayEvent';
-export type NotificationEventName = "click" | "foregroundWillDisplay";
+export type NotificationEventName = 'click' | 'foregroundWillDisplay';
export type NotificationEventTypeMap = {
click: NotificationClickedEvent;
@@ -17,6 +17,6 @@ export interface NotificationClickedEvent {
}
export interface ClickedEventAction {
- actionId ?: string;
+ actionId?: string;
type: ClickedEventActionType;
}
diff --git a/src/models/Subscription.ts b/src/models/Subscription.ts
index 5b3aefb7..80797f6b 100644
--- a/src/models/Subscription.ts
+++ b/src/models/Subscription.ts
@@ -3,7 +3,7 @@ export enum OSNotificationPermission {
Denied,
Authorized,
Provisional, // only available in iOS 12
- Ephemeral // only available in iOS 14
+ Ephemeral, // only available in iOS 14
}
export interface PushSubscription {
diff --git a/tsconfig.json b/tsconfig.json
index 108ebf59..4adec8ca 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -4,22 +4,14 @@
"target": "es5",
"moduleResolution": "node",
"noImplicitAny": true,
- "lib": [
- "es6"
- ],
+ "lib": ["es6"],
"rootDir": "src",
"declaration": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"esModuleInterop": true,
"strict": true,
- "noUnusedLocals": true,
+ "noUnusedLocals": true
},
- "exclude": [
- "node_modules",
- "dist",
- "android",
- "examples",
- "ios"
- ]
+ "exclude": ["node_modules", "dist", "android", "examples", "ios"]
}
From 8a99c3850dceeac7cb62e64a042bb302b516060c Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Tue, 27 Jun 2023 10:57:57 -0700
Subject: [PATCH 02/29] Migration guide fixes
---
MIGRATION_GUIDE.md | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md
index 3d1588c9..c93b5283 100644
--- a/MIGRATION_GUIDE.md
+++ b/MIGRATION_GUIDE.md
@@ -236,12 +236,12 @@ The Session namespace is accessible via `OneSignal.Session` and provides access
The Notifications namespace is accessible via `OneSignal.Notifications` and provides access to notification-scoped functionality.
-| **React Native** | **Description** |
-| -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **React Native** | **Description** |
+|--------------------------------------- | --------------- |
| `await OneSignal.Notifications.hasPermission()` | _Whether this app has push notification permission._ |
| `await OneSignal.Notifications.canRequestPermission()` | _Whether attempting to request notification permission will show a prompt. Returns `true` if the device has not been prompted for push notification permission already._ | `await OneSignal.Notifications.permissionNative()` | _(ios only) Returns the enum for the native permission of the device. It will be one of: NotDetermined, Denied, Authorized, Provisional (only available in iOS 12), Ephemeral (only available in iOS 14) _ |
| `OneSignal.Notifications.clearAll();` | _Removes all OneSignal notifications._ |
-| `OneSignal.Notifications.removeNotification("NOTIFICATION_ID")` | _(Android only) Cancels a single OneSignal notification based on its Android notification integer ID. Use instead of Android's [android.app.NotificationManager.cancel], otherwise the notification will be restored when your app is restarted._ |
+| `OneSignal.Notifications.removeNotification(32432)` | _(Android only) Cancels a single OneSignal notification based on its Android notification integer ID. Use instead of Android's [android.app.NotificationManager.cancel], otherwise the notification will be restored when your app is restarted._ |
| `OneSignal.Notifications.removeGroupedNotifications("GROUP_KEY")` | _(Android only) Cancels a group of OneSignal notifications with the provided group key. Grouping notifications is a OneSignal concept, there is no [android.app.NotificationManager] equivalent._ |
| `OneSignal.Notifications.requestPermission()`
**_See below for usage_** | _Prompt the user for permission to receive push notifications. This will display the native system prompt to request push notification permission._ |
| `OneSignal.Notifications.registerForProvisionalAuthorization()` | _(iOS only) Instead of having to prompt the user for permission to send them push notifications, your app can request provisional authorization._ |
@@ -313,7 +313,7 @@ console.log('Location shared: ', shared);
The In App Messages namespace is accessible via `OneSignal.InAppMessages` and provide access to in app messages-scoped functionality.
-| | **Description** |
+| **React Native** | **Description** |
| ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `await OneSignal.InAppMessages.getPaused()`
**_See below for usage_**
`OneSignal.InAppMessages.setPaused(true)` | _Whether in-app messaging is currently paused. When set to `true`, no IAM will be presented to the user regardless of whether they qualify for them. When set to `false`, any IAMs the user qualifies for will be presented to the user at the appropriate time._ |
| `OneSignal.InAppMessages.addTrigger("triggerKey", "triggerValue")` | _Add a trigger for the current user. Triggers are currently explicitly used to determine whether a specific IAM should be displayed to the user. See [Triggers](https://documentation.onesignal.com/docs/iam-triggers).
If the trigger key already exists, it will be replaced with the value provided here. Note that triggers are not persisted to the backend. They only exist on the local device and are applicable to the current user._ |
From 7dc08f70edcedd2b067c55797144c920b8375a46 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Thu, 29 Jun 2023 17:04:32 -0700
Subject: [PATCH 03/29] Update Migration Guide formatting
---
MIGRATION_GUIDE.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md
index c93b5283..a987cd62 100644
--- a/MIGRATION_GUIDE.md
+++ b/MIGRATION_GUIDE.md
@@ -143,7 +143,7 @@ The SDK is still accessible via a `OneSignal` static class. It provides access t
| **React Native** | **Description** |
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `OneSignal.initialize("YOUR_ONESIGNAL_APP_ID")` | _Initializes the OneSignal SDK. This should be called during startup of the application._ |
-| `OneSignal.User.login("USER_EXTERNAL_ID")` | \*Login to OneSignal under the user identified by the [externalId] provided. The act of logging a user into the OneSignal SDK will switch the [user] context to that specific user.
- If the [externalId] exists, the user will be retrieved and the context will be set from that user information. If operations have already been performed under a device-scoped user, they **_will not_** be applied to the now logged in user (they will be lost). - If the [externalId] does not exist the user, the user will be created and the context set from the current local state. If operations have already been performed under a device-scoped user, those operations **_will_** be applied to the newly created user.
**_Push Notifications and In App Messaging_** Logging in a new user will automatically transfer the push notification and in app messaging subscription from the current user (if there is one) to the newly logged in user. This is because both push notifications and in-app messages are owned by the device.\* |
+| `OneSignal.User.login("USER_EXTERNAL_ID")` | _Login to OneSignal under the user identified by the [externalId] provided. The act of logging a user into the OneSignal SDK will switch the [user] context to that specific user.
- If the [externalId] exists, the user will be retrieved and the context will be set from that user information. If operations have already been performed under a device-scoped user, they **_will not_** be applied to the now logged in user (they will be lost). - If the [externalId] does not exist the user, the user will be created and the context set from the current local state. If operations have already been performed under a device-scoped user, those operations **_will_** be applied to the newly created user.
**_Push Notifications and In App Messaging_** Logging in a new user will automatically transfer the push notification and in app messaging subscription from the current user (if there is one) to the newly logged in user. This is because both push notifications and in-app messages are owned by the device._ |
| `OneSignal.User.logout()` | _Logout the user previously logged in via [login]. The [user] property now references a new device-scoped user. A device-scoped user has no user identity that can later be retrieved, except through this device as long as the app remains installed and the app data is not cleared._ |
| `OneSignal.setConsentGiven(true)` | _Indicates whether privacy consent has been granted. This field is only relevant when the application has opted into data privacy protections. See [requiresPrivacyConsent]._ |
| `OneSignal.setConsentRequired(true)` | _Determines whether a user must consent to privacy prior to their user data being sent up to OneSignal. This should be set to `true` prior to the invocation of `initialize` to ensure compliance._ |
@@ -202,7 +202,7 @@ The Push Subscription namespace is accessible via `OneSignal.User.pushSubscripti
| --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `await OneSignal.User.PushSubscription.getId()` | _The readonly push subscription ID._ |
| `await OneSignal.User.PushSubscription.getToken()` | _The readonly push token._ |
-| `await OneSignal.User.PushSubscription.getOptedIn()` | \*Gets a boolean value indicating whether the current user is opted in to push notifications. This returns `true` when the app has notifications permission and `optedOut` is called. **_Note:_** Does not take into account the existence of the subscription ID and push token. This boolean may return `true` but push notifications may still not be received by the user.\* |
+| `await OneSignal.User.PushSubscription.getOptedIn()` | _Gets a boolean value indicating whether the current user is opted in to push notifications. This returns `true` when the app has notifications permission and `optedOut` is called. **_Note:_** Does not take into account the existence of the subscription ID and push token. This boolean may return `true` but push notifications may still not be received by the user._ |
| `OneSignal.User.PushSubscription.optIn()` | _Call this method to receive push notifications on the device or to resume receiving of push notifications after calling `optOut`. If needed, this method will prompt the user for push notifications permission._ |
| `OneSignal.User.PushSubscription.optOut()` | _If at any point you want the user to stop receiving push notifications on the current device (regardless of system-level permission status), you can call this method to opt out._ |
| `OneSignal.User.PushSubscription.addObserver(observer: (event) => void)`
**_See below for usage_** | _The `OSPushSubscriptionObserver.onOSPushSubscriptionChanged` method will be fired on the passed-in object when the push subscription changes. This method returns the current `OSPushSubscriptionState` at the time of adding this observer._ |
@@ -247,7 +247,7 @@ The Notifications namespace is accessible via `OneSignal.Notifications` and prov
| `OneSignal.Notifications.registerForProvisionalAuthorization()` | _(iOS only) Instead of having to prompt the user for permission to send them push notifications, your app can request provisional authorization._ |
| `OneSignal.Notifications.addPermissionObserver(observer)`
**_See below for usage_** | _This method will fire when a notification permission setting changes. This happens when the user enables or disables notifications for your app from the system settings outside of your app._ |
| `OneSignal.Notifications.removePermissionObserver(observer)`
**_See below for usage_** | _Remove a push permission observer that has been previously added._ |
-| `OneSignal.Notifications.addEventListener("foregroundWillDisplay", (event) => {};)`
**_See below for usage_** | \*Sets the handler to run before displaying a notification while the app is in focus. Use this handler to read notification data and change it or decide if the notification **_should_** show or not.
**_Note:_** this runs **_after_** the [Notification Service Extension](https://documentation.onesignal.com/docs/service-extensions) which can be used to modify the notification before showing it.\* |
+| `OneSignal.Notifications.addEventListener("foregroundWillDisplay", (event) => {};)`
**_See below for usage_** | _Sets the handler to run before displaying a notification while the app is in focus. Use this handler to read notification data and change it or decide if the notification **_should_** show or not.
**_Note:_** this runs **_after_** the [Notification Service Extension](https://documentation.onesignal.com/docs/service-extensions) which can be used to modify the notification before showing it._ |
| `OneSignal.Notifications.addEventListener("click", (event) => {};)`
**_See below for usage_** | _Sets a handler that will run whenever a notification is opened by the user._ |
### Prompt for Push Notification Permission
From 3b1949eab380d103b6bdb8d71182e9b91bb9088f Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 30 Jun 2023 17:10:50 -0700
Subject: [PATCH 04/29] Update Notification permission observer and
PushSubscription observer to be created via addEventListener methods
---
examples/RNOneSignalTS/src/OSDemo.tsx | 4 +--
src/events/EventManager.ts | 16 +++++++--
src/index.ts | 49 +++++++++++----------------
src/models/NotificationEvents.ts | 7 +++-
4 files changed, 40 insertions(+), 36 deletions(-)
diff --git a/examples/RNOneSignalTS/src/OSDemo.tsx b/examples/RNOneSignalTS/src/OSDemo.tsx
index e77b998c..afc6695d 100644
--- a/examples/RNOneSignalTS/src/OSDemo.tsx
+++ b/examples/RNOneSignalTS/src/OSDemo.tsx
@@ -89,11 +89,11 @@ class OSDemo extends React.Component {
this.OSLog('OneSignal: did dismiss IAM: ', event);
});
- OneSignal.User.PushSubscription.addObserver((subscription) => {
+ OneSignal.User.PushSubscription.addEventListener('change', (subscription) => {
this.OSLog('OneSignal: subscription changed:', subscription);
});
- OneSignal.Notifications.addPermissionObserver((granted) => {
+ OneSignal.Notifications.addEventListener('permissionChange', (granted) =>{
this.OSLog('OneSignal: permission changed:', granted.permission);
});
}
diff --git a/src/events/EventManager.ts b/src/events/EventManager.ts
index 400fda5b..b5aaf620 100644
--- a/src/events/EventManager.ts
+++ b/src/events/EventManager.ts
@@ -89,11 +89,21 @@ export default class EventManager {
/**
* clears the event handler(s) for the event name
* @param {string} eventName
+ * @param {function} handler
* @returns void
*/
- clearEventHandler(eventName: string) {
- this.eventHandlerArrayMap.delete(eventName);
- }
+ clearEventHandler(eventName: string, handler: any) {
+ let handlerArray = this.eventHandlerArrayMap.get(eventName);
+ if (handlerArray) {
+ const index = handlerArray.indexOf(handler);
+ if (index !== -1) {
+ handlerArray.splice(index, 1);
+ if (handlerArray.length === 0) {
+ this.eventHandlerArrayMap.delete(eventName);
+ }
+ }
+ }
+ }
// returns an event listener with the js to native mapping
generateEventListener(eventName: string): EmitterSubscription {
diff --git a/src/index.ts b/src/index.ts
index c903a02e..94e24c94 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -17,6 +17,7 @@ import {
NotificationEventName,
NotificationEventTypeMap,
NotificationClickedEvent,
+ PermissionChangedEvent
} from './models/NotificationEvents';
import {
PushSubscription,
@@ -53,7 +54,7 @@ let pushSubscription: PushSubscription = {
};
async function addPermissionObserver() {
- OneSignal.Notifications.addPermissionObserver((granted) => {
+ OneSignal.Notifications.addEventListener('permissionChange', (granted) => {
notificationPermission = granted.permission;
});
@@ -61,7 +62,7 @@ async function addPermissionObserver() {
}
async function addPushSubscriptionObserver() {
- OneSignal.User.PushSubscription.addObserver((subscriptionChange) => {
+ OneSignal.User.PushSubscription.addEventListener('change', (subscriptionChange) => {
pushSubscription = subscriptionChange;
});
@@ -202,23 +203,23 @@ export namespace OneSignal {
export namespace User {
export namespace PushSubscription {
/** Add a callback that fires when the OneSignal subscription state changes. */
- export function addObserver(handler: (event: PushSubscription) => void) {
+ export function addEventListener(event: 'change', listener: (event: PushSubscription) => void) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
- isValidCallback(handler);
+ isValidCallback(listener);
RNOneSignal.addPushSubscriptionObserver();
eventManager.addEventHandler(
SUBSCRIPTION_CHANGED,
- handler,
+ listener,
);
}
/** Clears current subscription observers. */
- export function removeObserver() {
+ export function removeEventListener(event: 'change', listener: (event: PushSubscription) => void) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
RNOneSignal.removePushSubscriptionObserver();
- eventManager.clearEventHandler(SUBSCRIPTION_CHANGED);
+ eventManager.clearEventHandler(SUBSCRIPTION_CHANGED, listener);
}
/** The readonly push subscription ID */
@@ -460,28 +461,6 @@ export namespace OneSignal {
}
}
- /** Add a callback that fires when the native push permission changes. */
- export function addPermissionObserver(
- observer: (event: { permission: boolean }) => void,
- ) {
- if (!isNativeModuleLoaded(RNOneSignal)) return;
-
- isValidCallback(observer);
- RNOneSignal.addPermissionObserver();
- eventManager.addEventHandler<{ permission: boolean }>(
- PERMISSION_CHANGED,
- observer,
- );
- }
-
- /** Remove permission observer that have been previously added. */
- export function removePermissionObserver() {
- if (!isNativeModuleLoaded(RNOneSignal)) return;
-
- RNOneSignal.removePermissionObserver();
- eventManager.clearEventHandler(PERMISSION_CHANGED);
- }
-
/** iOS Only.
* Returns the enum for the native permission of the device. It will be one of:
* OSNotificationPermissionNotDetermined,
@@ -529,6 +508,13 @@ export namespace OneSignal {
NOTIFICATION_WILL_DISPLAY,
listener as (event: NotificationWillDisplayEvent) => void,
);
+ } else if (event === "permissionChange") {
+ isValidCallback(listener);
+ RNOneSignal.addPermissionObserver();
+ eventManager.addEventHandler<{ permission: boolean }>(
+ PERMISSION_CHANGED,
+ listener as (event: PermissionChangedEvent) => void,
+ );
}
}
@@ -552,6 +538,9 @@ export namespace OneSignal {
if (index !== -1) {
_notificationWillDisplayListeners.splice(index, 1);
}
+ } else if (event === "permissionChange") {
+ RNOneSignal.removePermissionObserver();
+ eventManager.clearEventHandler(PERMISSION_CHANGED, listener);
} else {
return;
}
@@ -619,7 +608,7 @@ export namespace OneSignal {
) => void)[] = [];
/**
- * Add listeners for notification click and/or lifecycle events.
+ * Add listeners for In-App Message click and/or lifecycle events.
*/
export function addEventListener(
event: K,
diff --git a/src/models/NotificationEvents.ts b/src/models/NotificationEvents.ts
index 9829c726..8193ce0d 100644
--- a/src/models/NotificationEvents.ts
+++ b/src/models/NotificationEvents.ts
@@ -1,11 +1,12 @@
import OSNotification from '../OSNotification';
import NotificationWillDisplayEvent from '../events/NotificationWillDisplayEvent';
-export type NotificationEventName = 'click' | 'foregroundWillDisplay';
+export type NotificationEventName = "click" | "foregroundWillDisplay" | "permissionChange";
export type NotificationEventTypeMap = {
click: NotificationClickedEvent;
foregroundWillDisplay: NotificationWillDisplayEvent;
+ permissionChange: PermissionChangedEvent;
};
// 0 = NotificationClicked, 1 = ButtonClicked
@@ -20,3 +21,7 @@ export interface ClickedEventAction {
actionId?: string;
type: ClickedEventActionType;
}
+
+export interface PermissionChangedEvent {
+ permission: boolean;
+}
From c83d4782c85eb35eee8ab34f882034fd85bf51b0 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 30 Jun 2023 17:27:38 -0700
Subject: [PATCH 05/29] Update Migration Guide examples with new
addEventListener methods for PushSubscription and Notification permission
observers
---
MIGRATION_GUIDE.md | 27 +++++++++++++--------------
1 file changed, 13 insertions(+), 14 deletions(-)
diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md
index a987cd62..97d9a417 100644
--- a/MIGRATION_GUIDE.md
+++ b/MIGRATION_GUIDE.md
@@ -205,21 +205,21 @@ The Push Subscription namespace is accessible via `OneSignal.User.pushSubscripti
| `await OneSignal.User.PushSubscription.getOptedIn()` | _Gets a boolean value indicating whether the current user is opted in to push notifications. This returns `true` when the app has notifications permission and `optedOut` is called. **_Note:_** Does not take into account the existence of the subscription ID and push token. This boolean may return `true` but push notifications may still not be received by the user._ |
| `OneSignal.User.PushSubscription.optIn()` | _Call this method to receive push notifications on the device or to resume receiving of push notifications after calling `optOut`. If needed, this method will prompt the user for push notifications permission._ |
| `OneSignal.User.PushSubscription.optOut()` | _If at any point you want the user to stop receiving push notifications on the current device (regardless of system-level permission status), you can call this method to opt out._ |
-| `OneSignal.User.PushSubscription.addObserver(observer: (event) => void)`
**_See below for usage_** | _The `OSPushSubscriptionObserver.onOSPushSubscriptionChanged` method will be fired on the passed-in object when the push subscription changes. This method returns the current `OSPushSubscriptionState` at the time of adding this observer._ |
-| `OneSignal.User.PushSubscription.removeObserver(observer)`
**_See below for usage_** | _Remove a push subscription observer that has been previously added._ |
+| `OneSignal.User.PushSubscription.addEventListener('change', listener: (event) => void)`
**_See below for usage_** | _The `OSPushSubscriptionObserver.onPushSubscriptionDidChange` method will be fired on the passed-in object when the push subscription changes._ |
+| `OneSignal.User.PushSubscription.removeEventListener('change', listener)`
**_See below for usage_** | _Remove a push subscription observer that has been previously added._ |
### Push Subscription Observer
-Any object implementing the `OSPushSubscriptionObserver` protocol can be added as an observer. You can call `removeObserver` to remove any existing listeners.
+Any object implementing the `OSPushSubscriptionObserver` protocol can be added as an observer. You can call `removeEventListener` to remove any existing listeners.
```typescript
// Create an observer
-OneSignal.User.PushSubscription.addObserver((subscription) => {
- console.log('OneSignal: subscription changed: ', subscription);
+OneSignal.User.PushSubscription.addEventListener('change', (subscription) => {
+ console.log('OneSignal: subscription changed:', subscription);
});
// Removes the previously added observer
-OneSignal.User.PushSubscription.removeObserver(subscription);
+OneSignal.User.PushSubscription.removeEventListener('change', subscription);
```
## Session Namespace
@@ -245,8 +245,8 @@ The Notifications namespace is accessible via `OneSignal.Notifications` and prov
| `OneSignal.Notifications.removeGroupedNotifications("GROUP_KEY")` | _(Android only) Cancels a group of OneSignal notifications with the provided group key. Grouping notifications is a OneSignal concept, there is no [android.app.NotificationManager] equivalent._ |
| `OneSignal.Notifications.requestPermission()`
**_See below for usage_** | _Prompt the user for permission to receive push notifications. This will display the native system prompt to request push notification permission._ |
| `OneSignal.Notifications.registerForProvisionalAuthorization()` | _(iOS only) Instead of having to prompt the user for permission to send them push notifications, your app can request provisional authorization._ |
-| `OneSignal.Notifications.addPermissionObserver(observer)`
**_See below for usage_** | _This method will fire when a notification permission setting changes. This happens when the user enables or disables notifications for your app from the system settings outside of your app._ |
-| `OneSignal.Notifications.removePermissionObserver(observer)`
**_See below for usage_** | _Remove a push permission observer that has been previously added._ |
+| `OneSignal.Notifications.addEventListener("permissionChange", (observer) => {};)`
**_See below for usage_** | _This method will fire when a notification permission setting changes. This happens when the user enables or disables notifications for your app from the system settings outside of your app._ |
+| `OneSignal.Notifications.removeEventListener("permissionChange", (observer) => {};)`
**_See below for usage_** | _Remove a push permission observer that has been previously added._ |
| `OneSignal.Notifications.addEventListener("foregroundWillDisplay", (event) => {};)`
**_See below for usage_** | _Sets the handler to run before displaying a notification while the app is in focus. Use this handler to read notification data and change it or decide if the notification **_should_** show or not.
**_Note:_** this runs **_after_** the [Notification Service Extension](https://documentation.onesignal.com/docs/service-extensions) which can be used to modify the notification before showing it._ |
| `OneSignal.Notifications.addEventListener("click", (event) => {};)`
**_See below for usage_** | _Sets a handler that will run whenever a notification is opened by the user._ |
@@ -260,17 +260,16 @@ OneSignal.Notifications.requestPermission((accepted) => {
### Permission Observer
-Add an observer when permission status changes. You can call `removePermissionObserver` to remove any existing listeners.
+Add an observer when permission status changes. You can call `removeEventListener` to remove any existing listeners.
```typescript
// Add an observer
-let observer = function (req) {
- console.log('OneSignal: permission state changed to: ' + req);
-};
-OneSignal.Notifications.addPermissionObserver(observer);
+OneSignal.Notifications.addEventListener('permissionChange', (granted) =>{
+ console.log('OneSignal: permission changed:', granted.permission);
+});
// Remove previously added observer
-OneSignal.Notifications.removePermissionObserver(observer);
+OneSignal.Notifications.removeEventListener('permissionChange', observer);
```
### Notification Lifecycle Listener
From 118b343726b3f6c79016bec7150edca01afb78ce Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 30 Jun 2023 18:17:04 -0700
Subject: [PATCH 06/29] Run Prettier for new linting errors
---
examples/RNOneSignalTS/src/OSDemo.tsx | 11 +++++++----
src/events/EventManager.ts | 18 +++++++++---------
src/index.ts | 25 +++++++++++++++++--------
src/models/NotificationEvents.ts | 5 ++++-
4 files changed, 37 insertions(+), 22 deletions(-)
diff --git a/examples/RNOneSignalTS/src/OSDemo.tsx b/examples/RNOneSignalTS/src/OSDemo.tsx
index afc6695d..b9779d14 100644
--- a/examples/RNOneSignalTS/src/OSDemo.tsx
+++ b/examples/RNOneSignalTS/src/OSDemo.tsx
@@ -89,11 +89,14 @@ class OSDemo extends React.Component {
this.OSLog('OneSignal: did dismiss IAM: ', event);
});
- OneSignal.User.PushSubscription.addEventListener('change', (subscription) => {
- this.OSLog('OneSignal: subscription changed:', subscription);
- });
+ OneSignal.User.PushSubscription.addEventListener(
+ 'change',
+ (subscription) => {
+ this.OSLog('OneSignal: subscription changed:', subscription);
+ },
+ );
- OneSignal.Notifications.addEventListener('permissionChange', (granted) =>{
+ OneSignal.Notifications.addEventListener('permissionChange', (granted) => {
this.OSLog('OneSignal: permission changed:', granted.permission);
});
}
diff --git a/src/events/EventManager.ts b/src/events/EventManager.ts
index b5aaf620..8cf7a5d8 100644
--- a/src/events/EventManager.ts
+++ b/src/events/EventManager.ts
@@ -92,18 +92,18 @@ export default class EventManager {
* @param {function} handler
* @returns void
*/
- clearEventHandler(eventName: string, handler: any) {
- let handlerArray = this.eventHandlerArrayMap.get(eventName);
- if (handlerArray) {
- const index = handlerArray.indexOf(handler);
- if (index !== -1) {
- handlerArray.splice(index, 1);
- if (handlerArray.length === 0) {
- this.eventHandlerArrayMap.delete(eventName);
- }
+ clearEventHandler(eventName: string, handler: any) {
+ let handlerArray = this.eventHandlerArrayMap.get(eventName);
+ if (handlerArray) {
+ const index = handlerArray.indexOf(handler);
+ if (index !== -1) {
+ handlerArray.splice(index, 1);
+ if (handlerArray.length === 0) {
+ this.eventHandlerArrayMap.delete(eventName);
}
}
}
+ }
// returns an event listener with the js to native mapping
generateEventListener(eventName: string): EmitterSubscription {
diff --git a/src/index.ts b/src/index.ts
index 94e24c94..e6948ae6 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -17,7 +17,7 @@ import {
NotificationEventName,
NotificationEventTypeMap,
NotificationClickedEvent,
- PermissionChangedEvent
+ PermissionChangedEvent,
} from './models/NotificationEvents';
import {
PushSubscription,
@@ -62,9 +62,12 @@ async function addPermissionObserver() {
}
async function addPushSubscriptionObserver() {
- OneSignal.User.PushSubscription.addEventListener('change', (subscriptionChange) => {
- pushSubscription = subscriptionChange;
- });
+ OneSignal.User.PushSubscription.addEventListener(
+ 'change',
+ (subscriptionChange) => {
+ pushSubscription = subscriptionChange;
+ },
+ );
pushSubscription.id = await RNOneSignal.getPushSubscriptionId();
pushSubscription.token = await RNOneSignal.getPushSubscriptionToken();
@@ -203,7 +206,10 @@ export namespace OneSignal {
export namespace User {
export namespace PushSubscription {
/** Add a callback that fires when the OneSignal subscription state changes. */
- export function addEventListener(event: 'change', listener: (event: PushSubscription) => void) {
+ export function addEventListener(
+ event: 'change',
+ listener: (event: PushSubscription) => void,
+ ) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
isValidCallback(listener);
@@ -215,7 +221,10 @@ export namespace OneSignal {
}
/** Clears current subscription observers. */
- export function removeEventListener(event: 'change', listener: (event: PushSubscription) => void) {
+ export function removeEventListener(
+ event: 'change',
+ listener: (event: PushSubscription) => void,
+ ) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
RNOneSignal.removePushSubscriptionObserver();
@@ -508,7 +517,7 @@ export namespace OneSignal {
NOTIFICATION_WILL_DISPLAY,
listener as (event: NotificationWillDisplayEvent) => void,
);
- } else if (event === "permissionChange") {
+ } else if (event === 'permissionChange') {
isValidCallback(listener);
RNOneSignal.addPermissionObserver();
eventManager.addEventHandler<{ permission: boolean }>(
@@ -538,7 +547,7 @@ export namespace OneSignal {
if (index !== -1) {
_notificationWillDisplayListeners.splice(index, 1);
}
- } else if (event === "permissionChange") {
+ } else if (event === 'permissionChange') {
RNOneSignal.removePermissionObserver();
eventManager.clearEventHandler(PERMISSION_CHANGED, listener);
} else {
diff --git a/src/models/NotificationEvents.ts b/src/models/NotificationEvents.ts
index 8193ce0d..1d65fc28 100644
--- a/src/models/NotificationEvents.ts
+++ b/src/models/NotificationEvents.ts
@@ -1,7 +1,10 @@
import OSNotification from '../OSNotification';
import NotificationWillDisplayEvent from '../events/NotificationWillDisplayEvent';
-export type NotificationEventName = "click" | "foregroundWillDisplay" | "permissionChange";
+export type NotificationEventName =
+ | 'click'
+ | 'foregroundWillDisplay'
+ | 'permissionChange';
export type NotificationEventTypeMap = {
click: NotificationClickedEvent;
From 0fc4ba5ccad3b87cd7e7976c2d0bb81c734e2c33 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Mon, 10 Jul 2023 10:57:43 -0700
Subject: [PATCH 07/29] Update clearEventHandler method with early return
---
src/events/EventManager.ts | 21 +++++++++++----------
1 file changed, 11 insertions(+), 10 deletions(-)
diff --git a/src/events/EventManager.ts b/src/events/EventManager.ts
index 8cf7a5d8..3649899b 100644
--- a/src/events/EventManager.ts
+++ b/src/events/EventManager.ts
@@ -93,18 +93,19 @@ export default class EventManager {
* @returns void
*/
clearEventHandler(eventName: string, handler: any) {
- let handlerArray = this.eventHandlerArrayMap.get(eventName);
- if (handlerArray) {
- const index = handlerArray.indexOf(handler);
- if (index !== -1) {
- handlerArray.splice(index, 1);
- if (handlerArray.length === 0) {
- this.eventHandlerArrayMap.delete(eventName);
- }
- }
+ const handlerArray = this.eventHandlerArrayMap.get(eventName);
+ if (!handlerArray) {
+ return;
+ }
+ const index = handlerArray.indexOf(handler);
+ if (index !== -1) {
+ handlerArray.splice(index, 1);
+ }
+ if (handlerArray.length === 0) {
+ this.eventHandlerArrayMap.delete(eventName);
}
}
-
+
// returns an event listener with the js to native mapping
generateEventListener(eventName: string): EmitterSubscription {
const addListenerCallback = (payload: Object) => {
From c6cf5c5fe99607d5f3334953a6a35821d6f3d41e Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Mon, 10 Jul 2023 11:20:41 -0700
Subject: [PATCH 08/29] Fix lint error on EventManager class
---
src/events/EventManager.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/events/EventManager.ts b/src/events/EventManager.ts
index 3649899b..488828d2 100644
--- a/src/events/EventManager.ts
+++ b/src/events/EventManager.ts
@@ -105,7 +105,7 @@ export default class EventManager {
this.eventHandlerArrayMap.delete(eventName);
}
}
-
+
// returns an event listener with the js to native mapping
generateEventListener(eventName: string): EmitterSubscription {
const addListenerCallback = (payload: Object) => {
From 25b652c6d55d500956ea8badab6c1540c2c5d221 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 14 Jul 2023 18:37:46 -0700
Subject: [PATCH 09/29] Update Limitations and Notifications permission event
listener code sample
---
MIGRATION_GUIDE.md | 13 +++++--------
1 file changed, 5 insertions(+), 8 deletions(-)
diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md
index 97d9a417..2605f2c6 100644
--- a/MIGRATION_GUIDE.md
+++ b/MIGRATION_GUIDE.md
@@ -265,7 +265,7 @@ Add an observer when permission status changes. You can call `removeEventListene
```typescript
// Add an observer
OneSignal.Notifications.addEventListener('permissionChange', (granted) =>{
- console.log('OneSignal: permission changed:', granted.permission);
+ console.log('OneSignal: permission changed:', granted);
});
// Remove previously added observer
@@ -375,15 +375,12 @@ The Debug namespace is accessible via `OneSignal.Debug` and provide access to de
# Limitations
-**General**
-
-- Recommend using only in development and staging environments for Alpha releases
-- Aliases will be available in a future release
-- Outcomes will be available in a future release
-- Users are deleted when the last Subscription (push, email, or sms) is removed
+- This is a Beta release so please test thorougly prior to production use.
+- Changing app IDs is not supported.
- Any `User` namespace calls must be invoked **after** initialization. Example: `OneSignal.User.addTag("tag", "2")`
+- In the iOS SDK, the user state is only refreshed from the server when a new session is started (cold start or backgrounded for over 30 seconds) or when the user is logged in. This is by design.
# Known issues
- Identity Verification
- - We will be introducing JWT in a follow-up Beta release
+ - We will be introducing JWT in a follow-up Alpha or Beta release.
From 39ff2fede8cbf7f4b514d57f6c27ca86bf01a2c7 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 14 Jul 2023 18:49:51 -0700
Subject: [PATCH 10/29] Update iOS click listeners to be invoked by
sharedInstance
---
ios/RCTOneSignal/RCTOneSignal.h | 2 +-
ios/RCTOneSignal/RCTOneSignal.m | 8 +++++++
ios/RCTOneSignal/RCTOneSignalEventEmitter.m | 25 +++++++++------------
3 files changed, 20 insertions(+), 15 deletions(-)
diff --git a/ios/RCTOneSignal/RCTOneSignal.h b/ios/RCTOneSignal/RCTOneSignal.h
index 99ae3e94..ccf3336e 100644
--- a/ios/RCTOneSignal/RCTOneSignal.h
+++ b/ios/RCTOneSignal/RCTOneSignal.h
@@ -5,7 +5,7 @@
#import "../OneSignalFramework.h"
#endif
-@interface RCTOneSignal : NSObject
+@interface RCTOneSignal : NSObject
+ (RCTOneSignal *) sharedInstance;
diff --git a/ios/RCTOneSignal/RCTOneSignal.m b/ios/RCTOneSignal/RCTOneSignal.m
index dcaa9234..45bd4931 100644
--- a/ios/RCTOneSignal/RCTOneSignal.m
+++ b/ios/RCTOneSignal/RCTOneSignal.m
@@ -82,6 +82,14 @@ - (void)onNotificationPermissionDidChange:(BOOL)permission {
[self sendEvent:OSEventString(PermissionChanged) withBody:@{@"permission": @(permission)}];
}
+- (void)onClickNotification:(OSNotificationClickEvent * _Nonnull)event {
+ [self sendEvent:OSEventString(NotificationClicked) withBody:[event jsonRepresentation]];
+}
+
+- (void)onClickInAppMessage:(OSInAppMessageClickEvent * _Nonnull)event {
+ [self sendEvent:OSEventString(InAppMessageClicked) withBody:[event jsonRepresentation]];
+}
+
- (void)onWillDisplayInAppMessage:(OSInAppMessageWillDisplayEvent * _Nonnull)event {
[self sendEvent:OSEventString(InAppMessageWillDisplay) withBody:[event.message jsonRepresentation]];
}
diff --git a/ios/RCTOneSignal/RCTOneSignalEventEmitter.m b/ios/RCTOneSignal/RCTOneSignalEventEmitter.m
index be9b2ae2..a91c3db7 100644
--- a/ios/RCTOneSignal/RCTOneSignalEventEmitter.m
+++ b/ios/RCTOneSignal/RCTOneSignalEventEmitter.m
@@ -11,6 +11,9 @@ @implementation RCTOneSignalEventEmitter {
BOOL _hasSetPermissionObserver;
BOOL _hasSetEmailSubscriptionObserver;
BOOL _hasSetSMSSubscriptionObserver;
+ BOOL _hasAddedNotificationClickListener;
+ BOOL _hasAddedNotificationLifecycleListener;
+ BOOL _hasAddedInAppMessageClickListener;
BOOL _hasAddedInAppMessageLifecycleListener;
NSMutableDictionary* _preventDefaultCache;
NSMutableDictionary* _notificationWillDisplayCache;
@@ -183,13 +186,12 @@ + (void)sendEventWithName:(NSString *)name withBody:(NSDictionary *)body {
}
RCT_EXPORT_METHOD(addInAppMessageClickListener) {
- [OneSignal.InAppMessages addClickListener:self];
+ if (!_hasAddedInAppMessageClickListener) {
+ [OneSignal.InAppMessages addClickListener: [RCTOneSignal sharedInstance]];
+ _hasAddedInAppMessageClickListener = true;
+ }
}
-RCT_EXPORT_METHOD(onClickInAppMessage:(OSInAppMessageClickEvent * _Nonnull)event {
- [RCTOneSignalEventEmitter sendEventWithName:@"OneSignal-inAppMessageClicked" withBody:[event jsonRepresentation]];
-})
-
RCT_EXPORT_METHOD(addInAppMessagesLifecycleListener) {
if (!_hasAddedInAppMessageLifecycleListener) {
[OneSignal.InAppMessages addLifecycleListener:[RCTOneSignal sharedInstance]];
@@ -261,15 +263,10 @@ + (void)sendEventWithName:(NSString *)name withBody:(NSDictionary *)body {
}
RCT_EXPORT_METHOD(addNotificationClickListener) {
- [OneSignal.Notifications addClickListener:self];
-}
-
-RCT_EXPORT_METHOD(onClickNotification:(OSNotificationClickEvent * _Nonnull)event) {
- [RCTOneSignalEventEmitter sendEventWithName:@"OneSignal-notificationClicked" withBody:[event jsonRepresentation]];
-}
-
-RCT_EXPORT_METHOD(clearAllNotifications) {
- [OneSignal.Notifications clearAll];
+ if (!_hasAddedNotificationClickListener) {
+ [OneSignal.Notifications addClickListener:[RCTOneSignal sharedInstance]];
+ _hasAddedNotificationClickListener = true;
+ }
}
RCT_EXPORT_METHOD(addNotificationForegroundLifecycleListener) {
From 164d3242a9e5b06ec75688b2b6d22a5db9f94151 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 14 Jul 2023 18:54:34 -0700
Subject: [PATCH 11/29] Remove old Email and SMS observers from iOS Event
Emitter.
---
ios/RCTOneSignal/RCTOneSignalEventEmitter.m | 16 ----------------
1 file changed, 16 deletions(-)
diff --git a/ios/RCTOneSignal/RCTOneSignalEventEmitter.m b/ios/RCTOneSignal/RCTOneSignalEventEmitter.m
index a91c3db7..7d56dec6 100644
--- a/ios/RCTOneSignal/RCTOneSignalEventEmitter.m
+++ b/ios/RCTOneSignal/RCTOneSignalEventEmitter.m
@@ -9,8 +9,6 @@ @implementation RCTOneSignalEventEmitter {
BOOL _hasListeners;
BOOL _hasSetSubscriptionObserver;
BOOL _hasSetPermissionObserver;
- BOOL _hasSetEmailSubscriptionObserver;
- BOOL _hasSetSMSSubscriptionObserver;
BOOL _hasAddedNotificationClickListener;
BOOL _hasAddedNotificationLifecycleListener;
BOOL _hasAddedInAppMessageClickListener;
@@ -323,20 +321,6 @@ + (void)sendEventWithName:(NSString *)name withBody:(NSDictionary *)body {
}
}
-RCT_EXPORT_METHOD(addEmail) {
- if (!_hasSetEmailSubscriptionObserver) {
- [OneSignal.User addEmail:[RCTOneSignal sharedInstance]];
- _hasSetEmailSubscriptionObserver = true;
- }
-}
-
-RCT_EXPORT_METHOD(removeEmail) {
- if (_hasSetEmailSubscriptionObserver) {
- [OneSignal.User removeEmail:[RCTOneSignal sharedInstance]];
- _hasSetEmailSubscriptionObserver = false;
- }
-}
-
RCT_EXPORT_METHOD(setLanguage:(NSString *)language) {
[OneSignal.User setLanguage:language];
}
From 3670e4f676443cbe5a6bf8fa1adaae8aa1edcf37 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 14 Jul 2023 19:09:22 -0700
Subject: [PATCH 12/29] Update PushSubscription interfaces, properties, and
functions
---
ios/RCTOneSignal/RCTOneSignal.m | 2 +-
src/index.ts | 17 +++++++++--------
src/models/Subscription.ts | 7 ++++++-
3 files changed, 16 insertions(+), 10 deletions(-)
diff --git a/ios/RCTOneSignal/RCTOneSignal.m b/ios/RCTOneSignal/RCTOneSignal.m
index 45bd4931..277f5e13 100644
--- a/ios/RCTOneSignal/RCTOneSignal.m
+++ b/ios/RCTOneSignal/RCTOneSignal.m
@@ -75,7 +75,7 @@ - (void)sendEvent:(NSString *)eventName withBody:(NSDictionary *)body {
}
- (void)onPushSubscriptionDidChangeWithState:(OSPushSubscriptionChangedState * _Nonnull)state {
- [self sendEvent:OSEventString(SubscriptionChanged) withBody:[state.current jsonRepresentation]];
+ [self sendEvent:OSEventString(SubscriptionChanged) withBody:[state jsonRepresentation]];
}
- (void)onNotificationPermissionDidChange:(BOOL)permission {
diff --git a/src/index.ts b/src/index.ts
index e6948ae6..cba003c4 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -20,8 +20,9 @@ import {
PermissionChangedEvent,
} from './models/NotificationEvents';
import {
- PushSubscription,
+ PushSubscriptionState,
OSNotificationPermission,
+ PushSubscriptionChangedState
} from './models/Subscription';
import NotificationWillDisplayEvent from './events/NotificationWillDisplayEvent';
import { OutcomeEvent } from './models/Outcomes';
@@ -47,7 +48,7 @@ export type LogLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6;
let notificationPermission = false;
// Internal wrapper push subscription state that is being updated by the subscription change handler.
-let pushSubscription: PushSubscription = {
+let pushSubscription: PushSubscriptionState = {
id: '',
token: '',
optedIn: false,
@@ -61,11 +62,11 @@ async function addPermissionObserver() {
notificationPermission = await RNOneSignal.hasNotificationPermission();
}
-async function addPushSubscriptionObserver() {
+async function _addPushSubscriptionObserver() {
OneSignal.User.PushSubscription.addEventListener(
'change',
(subscriptionChange) => {
- pushSubscription = subscriptionChange;
+ pushSubscription = subscriptionChange.current;
},
);
@@ -82,7 +83,7 @@ export namespace OneSignal {
RNOneSignal.initialize(appId);
addPermissionObserver();
- addPushSubscriptionObserver();
+ _addPushSubscriptionObserver();
}
/**
@@ -208,13 +209,13 @@ export namespace OneSignal {
/** Add a callback that fires when the OneSignal subscription state changes. */
export function addEventListener(
event: 'change',
- listener: (event: PushSubscription) => void,
+ listener: (event: PushSubscriptionChangedState) => void,
) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
isValidCallback(listener);
RNOneSignal.addPushSubscriptionObserver();
- eventManager.addEventHandler(
+ eventManager.addEventHandler(
SUBSCRIPTION_CHANGED,
listener,
);
@@ -223,7 +224,7 @@ export namespace OneSignal {
/** Clears current subscription observers. */
export function removeEventListener(
event: 'change',
- listener: (event: PushSubscription) => void,
+ listener: (event: PushSubscriptionChangedState) => void,
) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
diff --git a/src/models/Subscription.ts b/src/models/Subscription.ts
index 80797f6b..97119cd7 100644
--- a/src/models/Subscription.ts
+++ b/src/models/Subscription.ts
@@ -6,8 +6,13 @@ export enum OSNotificationPermission {
Ephemeral, // only available in iOS 14
}
-export interface PushSubscription {
+export interface PushSubscriptionState {
id: string;
token: string;
optedIn: boolean;
}
+
+export interface PushSubscriptionChangedState {
+ previous: PushSubscriptionState
+ current: PushSubscriptionState
+}
From f0fb0f04ddc10706b75954a5d8dfa51a678dc222 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 14 Jul 2023 19:31:04 -0700
Subject: [PATCH 13/29] Delete native call to removePushSubscriptionObserver
---
src/index.ts | 1 -
1 file changed, 1 deletion(-)
diff --git a/src/index.ts b/src/index.ts
index cba003c4..8c51b370 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -228,7 +228,6 @@ export namespace OneSignal {
) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
- RNOneSignal.removePushSubscriptionObserver();
eventManager.clearEventHandler(SUBSCRIPTION_CHANGED, listener);
}
From dfc58cac0c8414e04599d97fdaf4a467b8240c7c Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 14 Jul 2023 19:37:43 -0700
Subject: [PATCH 14/29] Update InAppMessages listeners to be handled by
EventManager
---
src/index.ts | 74 +++++++---------------------------------------------
1 file changed, 10 insertions(+), 64 deletions(-)
diff --git a/src/index.ts b/src/index.ts
index 8c51b370..7e0ed485 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -600,22 +600,6 @@ export namespace OneSignal {
}
export namespace InAppMessages {
- export const _inAppMessageClickListeners: ((
- action: InAppMessageClickEvent,
- ) => void)[] = [];
- export const _willDisplayInAppMessageListeners: ((
- event: InAppMessageWillDisplayEvent,
- ) => void)[] = [];
- export const _didDisplayInAppMessageListeners: ((
- event: InAppMessageDidDisplayEvent,
- ) => void)[] = [];
- export const _willDismissInAppMessageListeners: ((
- event: InAppMessageWillDismissEvent,
- ) => void)[] = [];
- export const _didDismissInAppMessageListeners: ((
- event: InAppMessageDidDismissEvent,
- ) => void)[] = [];
-
/**
* Add listeners for In-App Message click and/or lifecycle events.
*/
@@ -629,48 +613,33 @@ export namespace OneSignal {
if (event === 'click') {
isValidCallback(listener);
- _inAppMessageClickListeners.push(
- listener as (event: InAppMessageClickEvent) => void,
- );
RNOneSignal.addInAppMessageClickListener();
- eventManager.setEventHandler(
+ eventManager.addEventHandler(
IN_APP_MESSAGE_CLICKED,
listener as (event: InAppMessageClickEvent) => void,
);
} else {
if (event === 'willDisplay') {
isValidCallback(listener);
- _willDisplayInAppMessageListeners.push(
- listener as (event: InAppMessageWillDisplayEvent) => void,
- );
- eventManager.setEventHandler(
+ eventManager.addEventHandler(
IN_APP_MESSAGE_WILL_DISPLAY,
listener as (event: InAppMessageWillDisplayEvent) => void,
);
} else if (event === 'didDisplay') {
isValidCallback(listener);
- _didDisplayInAppMessageListeners.push(
- listener as (event: InAppMessageDidDisplayEvent) => void,
- );
- eventManager.setEventHandler(
+ eventManager.addEventHandler(
IN_APP_MESSAGE_DID_DISPLAY,
listener as (event: InAppMessageDidDisplayEvent) => void,
);
} else if (event === 'willDismiss') {
isValidCallback(listener);
- _willDismissInAppMessageListeners.push(
- listener as (event: InAppMessageWillDismissEvent) => void,
- );
- eventManager.setEventHandler(
+ eventManager.addEventHandler(
IN_APP_MESSAGE_WILL_DISMISS,
listener as (event: InAppMessageWillDismissEvent) => void,
);
} else if (event === 'didDismiss') {
isValidCallback(listener);
- _didDismissInAppMessageListeners.push(
- listener as (event: InAppMessageDidDismissEvent) => void,
- );
- eventManager.setEventHandler(
+ eventManager.addEventHandler(
IN_APP_MESSAGE_DID_DISMISS,
listener as (event: InAppMessageDidDismissEvent) => void,
);
@@ -689,39 +658,16 @@ export namespace OneSignal {
listener: (obj: InAppMessageEventTypeMap[K]) => void,
): void {
if (event === 'click') {
- const index = _inAppMessageClickListeners.indexOf(listener);
- if (index !== -1) {
- _inAppMessageClickListeners.splice(index, 1);
- }
+ eventManager.clearEventHandler(IN_APP_MESSAGE_CLICKED, listener);
} else {
if (event === 'willDisplay') {
- let index = _willDisplayInAppMessageListeners.indexOf(
- listener as (event: InAppMessageWillDisplayEvent) => void,
- );
- if (index !== -1) {
- _willDisplayInAppMessageListeners.splice(index, 1);
- }
+ eventManager.clearEventHandler(IN_APP_MESSAGE_WILL_DISPLAY, listener);
} else if (event === 'didDisplay') {
- let index = _didDisplayInAppMessageListeners.indexOf(
- listener as (event: InAppMessageDidDisplayEvent) => void,
- );
- if (index !== -1) {
- _willDisplayInAppMessageListeners.splice(index, 1);
- }
+ eventManager.clearEventHandler(IN_APP_MESSAGE_DID_DISPLAY, listener);
} else if (event === 'willDismiss') {
- let index = _willDismissInAppMessageListeners.indexOf(
- listener as (event: InAppMessageWillDismissEvent) => void,
- );
- if (index !== -1) {
- _willDismissInAppMessageListeners.splice(index, 1);
- }
+ eventManager.clearEventHandler(IN_APP_MESSAGE_WILL_DISMISS, listener);
} else if (event === 'didDismiss') {
- let index = _didDismissInAppMessageListeners.indexOf(
- listener as (event: InAppMessageDidDismissEvent) => void,
- );
- if (index !== -1) {
- _didDismissInAppMessageListeners.splice(index, 1);
- }
+ eventManager.clearEventHandler(IN_APP_MESSAGE_DID_DISMISS, listener);
} else {
return;
}
From 7e10dbf7fc28e247492689bec1bfc144c3902724 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 14 Jul 2023 19:50:10 -0700
Subject: [PATCH 15/29] Update Notification event interfaces and methods
Notification listeners to be handled by EventManager
---
examples/RNOneSignalTS/src/OSDemo.tsx | 2 +-
ios/RCTOneSignal/RCTOneSignal.m | 8 ++--
src/index.ts | 64 +++++++++------------------
src/models/NotificationEvents.ts | 19 +++-----
4 files changed, 31 insertions(+), 62 deletions(-)
diff --git a/examples/RNOneSignalTS/src/OSDemo.tsx b/examples/RNOneSignalTS/src/OSDemo.tsx
index b9779d14..6b9a3dcb 100644
--- a/examples/RNOneSignalTS/src/OSDemo.tsx
+++ b/examples/RNOneSignalTS/src/OSDemo.tsx
@@ -97,7 +97,7 @@ class OSDemo extends React.Component {
);
OneSignal.Notifications.addEventListener('permissionChange', (granted) => {
- this.OSLog('OneSignal: permission changed:', granted.permission);
+ this.OSLog('OneSignal: permission changed:', granted);
});
}
diff --git a/ios/RCTOneSignal/RCTOneSignal.m b/ios/RCTOneSignal/RCTOneSignal.m
index 277f5e13..004a9dc6 100644
--- a/ios/RCTOneSignal/RCTOneSignal.m
+++ b/ios/RCTOneSignal/RCTOneSignal.m
@@ -91,19 +91,19 @@ - (void)onClickInAppMessage:(OSInAppMessageClickEvent * _Nonnull)event {
}
- (void)onWillDisplayInAppMessage:(OSInAppMessageWillDisplayEvent * _Nonnull)event {
- [self sendEvent:OSEventString(InAppMessageWillDisplay) withBody:[event.message jsonRepresentation]];
+ [self sendEvent:OSEventString(InAppMessageWillDisplay) withBody:@{@"message": [event.message jsonRepresentation]}];
}
- (void)onDidDisplayInAppMessage:(OSInAppMessageDidDisplayEvent * _Nonnull)event {
- [self sendEvent:OSEventString(InAppMessageDidDisplay) withBody:[event.message jsonRepresentation]];
+ [self sendEvent:OSEventString(InAppMessageDidDisplay) withBody:@{@"message": [event.message jsonRepresentation]}];
}
- (void)onWillDismissInAppMessage:(OSInAppMessageWillDismissEvent * _Nonnull)event {
- [self sendEvent:OSEventString(InAppMessageWillDismiss) withBody:[event.message jsonRepresentation]];
+ [self sendEvent:OSEventString(InAppMessageWillDismiss) withBody:@{@"message": [event.message jsonRepresentation]}];
}
- (void)onDidDismissInAppMessage:(OSInAppMessageDidDismissEvent * _Nonnull)event {
- [self sendEvent:OSEventString(InAppMessageDidDismiss) withBody:[event.message jsonRepresentation]];
+ [self sendEvent:OSEventString(InAppMessageDidDismiss) withBody:@{@"message": [event.message jsonRepresentation]}];
}
- (void)dealloc {
diff --git a/src/index.ts b/src/index.ts
index 7e0ed485..6e1a1f5a 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -16,8 +16,7 @@ import {
import {
NotificationEventName,
NotificationEventTypeMap,
- NotificationClickedEvent,
- PermissionChangedEvent,
+ NotificationClickEvent,
} from './models/NotificationEvents';
import {
PushSubscriptionState,
@@ -54,9 +53,9 @@ let pushSubscription: PushSubscriptionState = {
optedIn: false,
};
-async function addPermissionObserver() {
+async function _addPermissionObserver() {
OneSignal.Notifications.addEventListener('permissionChange', (granted) => {
- notificationPermission = granted.permission;
+ notificationPermission = granted;
});
notificationPermission = await RNOneSignal.hasNotificationPermission();
@@ -82,7 +81,7 @@ export namespace OneSignal {
RNOneSignal.initialize(appId);
- addPermissionObserver();
+ _addPermissionObserver();
_addPushSubscriptionObserver();
}
@@ -408,13 +407,6 @@ export namespace OneSignal {
}
export namespace Notifications {
- export const _notificationClickedListeners: ((
- action: NotificationClickedEvent,
- ) => void)[] = [];
- export const _notificationWillDisplayListeners: ((
- notification: NotificationWillDisplayEvent,
- ) => void)[] = [];
-
/**
* Whether this app has push notification permission. Returns true if the user has accepted permissions,
* or if the app has ephemeral or provisional permission.
@@ -478,15 +470,17 @@ export namespace OneSignal {
* OSNotificationPermissionProvisional - only available in iOS 12,
* OSNotificationPermissionEphemeral - only available in iOS 14
* */
- export function permissionNative() {
- if (!isNativeModuleLoaded(RNOneSignal)) return;
+ export function permissionNative(): Promise {
+ if (!isNativeModuleLoaded(RNOneSignal)) {
+ return Promise.reject(new Error('OneSignal native module not loaded'));;
+ }
if (Platform.OS === 'ios') {
return RNOneSignal.permissionNative();
} else {
return notificationPermission
- ? OSNotificationPermission.Authorized
- : OSNotificationPermission.Denied;
+ ? Promise.resolve(OSNotificationPermission.Authorized)
+ : Promise.resolve(OSNotificationPermission.Denied);
}
}
@@ -500,29 +494,23 @@ export namespace OneSignal {
isValidCallback(listener);
if (event === 'click') {
- _notificationClickedListeners.push(
- listener as (event: NotificationClickedEvent) => void,
- );
RNOneSignal.addNotificationClickListener();
- eventManager.setEventHandler(
+ eventManager.addEventHandler(
NOTIFICATION_CLICKED,
- listener as (event: NotificationClickedEvent) => void,
+ listener as (event: NotificationClickEvent) => void,
);
} else if (event === 'foregroundWillDisplay') {
- _notificationWillDisplayListeners.push(
- listener as (event: NotificationWillDisplayEvent) => void,
- );
RNOneSignal.addNotificationForegroundLifecycleListener();
- eventManager.setEventHandler(
+ eventManager.addEventHandler(
NOTIFICATION_WILL_DISPLAY,
listener as (event: NotificationWillDisplayEvent) => void,
);
} else if (event === 'permissionChange') {
isValidCallback(listener);
RNOneSignal.addPermissionObserver();
- eventManager.addEventHandler<{ permission: boolean }>(
+ eventManager.addEventHandler(
PERMISSION_CHANGED,
- listener as (event: PermissionChangedEvent) => void,
+ listener as (event: boolean) => void,
);
}
}
@@ -531,24 +519,13 @@ export namespace OneSignal {
* Remove listeners for notification click and/or lifecycle events. */
export function removeEventListener(
event: K,
- listener: (obj: NotificationEventTypeMap[K]) => void,
+ listener: (event: NotificationEventTypeMap[K]) => void,
): void {
if (event === 'click') {
- let index = _notificationClickedListeners.indexOf(
- listener as (event: NotificationClickedEvent) => void,
- );
- if (index !== -1) {
- _notificationClickedListeners.splice(index, 1);
- }
+ eventManager.clearEventHandler(NOTIFICATION_CLICKED, listener);
} else if (event === 'foregroundWillDisplay') {
- let index = _notificationWillDisplayListeners.indexOf(
- listener as (event: NotificationWillDisplayEvent) => void,
- );
- if (index !== -1) {
- _notificationWillDisplayListeners.splice(index, 1);
- }
+ eventManager.clearEventHandler(NOTIFICATION_WILL_DISPLAY, listener);
} else if (event === 'permissionChange') {
- RNOneSignal.removePermissionObserver();
eventManager.clearEventHandler(PERMISSION_CHANGED, listener);
} else {
return;
@@ -808,7 +785,7 @@ export namespace OneSignal {
export {
NotificationWillDisplayEvent,
- NotificationClickedEvent,
+ NotificationClickEvent,
InAppMessage,
InAppMessageClickEvent,
InAppMessageWillDisplayEvent,
@@ -820,7 +797,6 @@ export {
export { default as OSNotification } from './OSNotification';
export {
- ClickedEventAction,
- ClickedEventActionType,
+ NotificationClickResult,
} from './models/NotificationEvents';
export { OSNotificationPermission } from './models/Subscription';
diff --git a/src/models/NotificationEvents.ts b/src/models/NotificationEvents.ts
index 1d65fc28..281e8b11 100644
--- a/src/models/NotificationEvents.ts
+++ b/src/models/NotificationEvents.ts
@@ -7,24 +7,17 @@ export type NotificationEventName =
| 'permissionChange';
export type NotificationEventTypeMap = {
- click: NotificationClickedEvent;
+ click: NotificationClickEvent;
foregroundWillDisplay: NotificationWillDisplayEvent;
- permissionChange: PermissionChangedEvent;
+ permissionChange: boolean;
};
-// 0 = NotificationClicked, 1 = ButtonClicked
-export type ClickedEventActionType = 0 | 1;
-
-export interface NotificationClickedEvent {
- action: ClickedEventAction;
+export interface NotificationClickEvent {
+ result: NotificationClickResult;
notification: OSNotification;
}
-export interface ClickedEventAction {
+export interface NotificationClickResult {
actionId?: string;
- type: ClickedEventActionType;
-}
-
-export interface PermissionChangedEvent {
- permission: boolean;
+ url?: string;
}
From 762ee2b05d3c4c6e272c7c4a3b994f0e00575b59 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 14 Jul 2023 20:03:28 -0700
Subject: [PATCH 16/29] Update Android Notification and IAM listeners to send
entire event
---
.../rnonesignalandroid/RNOneSignal.java | 38 +++---
.../geektime/rnonesignalandroid/RNUtils.java | 117 +++++++++++++-----
2 files changed, 109 insertions(+), 46 deletions(-)
diff --git a/android/src/main/java/com/geektime/rnonesignalandroid/RNOneSignal.java b/android/src/main/java/com/geektime/rnonesignalandroid/RNOneSignal.java
index 712e28f0..460de719 100644
--- a/android/src/main/java/com/geektime/rnonesignalandroid/RNOneSignal.java
+++ b/android/src/main/java/com/geektime/rnonesignalandroid/RNOneSignal.java
@@ -93,13 +93,14 @@ public class RNOneSignal extends ReactContextBaseJavaModule implements
private boolean hasAddedNotificationForegroundListener = false;
private boolean hasAddedInAppMessageLifecycleListener = false;
+ private boolean hasAddedNotificationClickListener = false;
+ private boolean hasAddedInAppMessageClickListener = false;
private IInAppMessageClickListener rnInAppClickListener = new IInAppMessageClickListener() {
@Override
public void onClick(IInAppMessageClickEvent event) {
try {
- IInAppMessageClickResult result = event.getResult();
- sendEvent("OneSignal-inAppMessageClicked", RNUtils.convertHashMapToWritableMap(RNUtils.convertInAppMessageClickResultToMap(result)));
+ sendEvent("OneSignal-inAppMessageClicked", RNUtils.convertHashMapToWritableMap(RNUtils.convertInAppMessageClickEventToMap(event)));
} catch (JSONException e) {
e.printStackTrace();
}
@@ -110,7 +111,7 @@ public void onClick(IInAppMessageClickEvent event) {
@Override
public void onWillDisplay(IInAppMessageWillDisplayEvent event) {
try {
- sendEvent("OneSignal-inAppMessageWillDisplay", RNUtils.convertHashMapToWritableMap(RNUtils.convertInAppMessageToMap(event.getMessage())));
+ sendEvent("OneSignal-inAppMessageWillDisplay", RNUtils.convertHashMapToWritableMap(RNUtils.convertInAppMessageWillDisplayEventToMap(event)));
} catch (JSONException e) {
e.printStackTrace();
}
@@ -119,7 +120,7 @@ public void onWillDisplay(IInAppMessageWillDisplayEvent event) {
@Override
public void onDidDisplay(IInAppMessageDidDisplayEvent event) {
try {
- sendEvent("OneSignal-inAppMessageDidDisplay", RNUtils.convertHashMapToWritableMap(RNUtils.convertInAppMessageToMap(event.getMessage())));
+ sendEvent("OneSignal-inAppMessageDidDisplay", RNUtils.convertHashMapToWritableMap(RNUtils.convertInAppMessageDidDisplayEventToMap(event)));
} catch (JSONException e) {
e.printStackTrace();
}
@@ -128,7 +129,7 @@ public void onDidDisplay(IInAppMessageDidDisplayEvent event) {
@Override
public void onWillDismiss(IInAppMessageWillDismissEvent event) {
try {
- sendEvent("OneSignal-inAppMessageWillDismiss", RNUtils.convertHashMapToWritableMap(RNUtils.convertInAppMessageToMap(event.getMessage())));
+ sendEvent("OneSignal-inAppMessageWillDismiss", RNUtils.convertHashMapToWritableMap(RNUtils.convertInAppMessageWillDismissEventToMap(event)));
} catch (JSONException e) {
e.printStackTrace();
}
@@ -137,7 +138,7 @@ public void onWillDismiss(IInAppMessageWillDismissEvent event) {
@Override
public void onDidDismiss(IInAppMessageDidDismissEvent event) {
try {
- sendEvent("OneSignal-inAppMessageDidDismiss", RNUtils.convertHashMapToWritableMap(RNUtils.convertInAppMessageToMap(event.getMessage())));
+ sendEvent("OneSignal-inAppMessageDidDismiss", RNUtils.convertHashMapToWritableMap(RNUtils.convertInAppMessageDidDismissEventToMap(event)));
} catch (JSONException e) {
e.printStackTrace();
}
@@ -148,7 +149,7 @@ public void onDidDismiss(IInAppMessageDidDismissEvent event) {
@Override
public void onClick(INotificationClickEvent event) {
try {
- sendEvent("OneSignal-notificationClicked", RNUtils.convertHashMapToWritableMap(RNUtils.convertNotificationToMap(event.getNotification())));
+ sendEvent("OneSignal-notificationClicked", RNUtils.convertHashMapToWritableMap(RNUtils.convertNotificationClickEventToMap(event)));
} catch (JSONException e) {
e.printStackTrace();
}
@@ -162,19 +163,19 @@ private void removeObservers() {
private void removeHandlers() {
OneSignal.getInAppMessages().removeClickListener(rnInAppClickListener);
+ hasAddedInAppMessageClickListener = false;
OneSignal.getInAppMessages().removeLifecycleListener(rnInAppLifecycleListener);
+ hasAddedInAppMessageLifecycleListener = false;
OneSignal.getNotifications().removeClickListener(rnNotificationClickListener);
+ hasAddedNotificationClickListener = false;
OneSignal.getNotifications().removeForegroundLifecycleListener(this);
+ hasAddedNotificationForegroundListener = false;
}
private void sendEvent(String eventName, Object params) {
mReactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
}
- private void initNotificationWillDisplayInForegroundListenerParams() {
- this.hasAddedNotificationForegroundListener = true;
- }
-
public RNOneSignal(ReactApplicationContext reactContext) {
super(reactContext);
mReactApplicationContext = reactContext;
@@ -256,7 +257,10 @@ public void setAlertLevel(int logLevel) {
// OneSignal.InAppMessages namespace methods
@ReactMethod
public void addInAppMessageClickListener() {
- OneSignal.getInAppMessages().addClickListener(rnInAppClickListener);
+ if (!hasAddedInAppMessageClickListener) {
+ OneSignal.getInAppMessages().addClickListener(rnInAppClickListener);
+ hasAddedInAppMessageClickListener = true;
+ }
}
@ReactMethod
@@ -323,7 +327,12 @@ public void setLocationShared(Boolean shared) {
// OneSignal.Notifications namespace methods
@ReactMethod
public void addNotificationClickListener() {
+ if (this.hasAddedNotificationClickListener) {
+ return;
+ }
+
OneSignal.getNotifications().addClickListener(rnNotificationClickListener);
+ hasAddedNotificationClickListener = true;
}
@ReactMethod
@@ -342,15 +351,14 @@ public void onWillDisplay(INotificationWillDisplayEvent event) {
event.getNotification().display();
}
- INotification notification = event.getNotification();
- String notificationId = notification.getNotificationId();
+ String notificationId = event.getNotification().getNotificationId();
notificationWillDisplayCache.put(notificationId, (INotificationWillDisplayEvent) event);
event.preventDefault();
try {
sendEvent("OneSignal-notificationWillDisplayInForeground",
RNUtils.convertHashMapToWritableMap(
- RNUtils.convertNotificationToMap(notification)));
+ RNUtils.convertNotificationEventToMap(event)));
try {
synchronized (event) {
diff --git a/android/src/main/java/com/geektime/rnonesignalandroid/RNUtils.java b/android/src/main/java/com/geektime/rnonesignalandroid/RNUtils.java
index eeac44fb..511145e4 100644
--- a/android/src/main/java/com/geektime/rnonesignalandroid/RNUtils.java
+++ b/android/src/main/java/com/geektime/rnonesignalandroid/RNUtils.java
@@ -13,12 +13,15 @@
import com.facebook.react.bridge.WritableNativeMap;
import com.onesignal.inAppMessages.IInAppMessage;
+import com.onesignal.inAppMessages.IInAppMessageClickEvent;
import com.onesignal.inAppMessages.IInAppMessageClickResult;
import com.onesignal.inAppMessages.IInAppMessageWillDisplayEvent;
import com.onesignal.inAppMessages.IInAppMessageDidDisplayEvent;
import com.onesignal.inAppMessages.IInAppMessageWillDismissEvent;
import com.onesignal.inAppMessages.IInAppMessageDidDismissEvent;
import com.onesignal.notifications.INotification;
+import com.onesignal.notifications.INotificationWillDisplayEvent;
+import com.onesignal.notifications.INotificationClickEvent;
import com.onesignal.notifications.INotificationClickResult;
import com.onesignal.notifications.INotificationReceivedEvent;
import com.onesignal.user.subscriptions.IPushSubscription;
@@ -61,71 +64,123 @@ public static WritableMap convertHashMapToWritableMap(HashMap ha
return writableMap;
}
- public static HashMap convertNotificationToMap(INotification notification) throws JSONException {
+ public static HashMap convertNotificationWillDisplayEventToMap(INotificationWillDisplayEvent event) throws JSONException {
+ HashMap notificationHash = convertNotificationEventToMap(event.getNotification());
+
+ return notificationHash;
+ }
+
+ public static HashMap convertNotificationClickEventToMap(INotificationClickEvent event) throws JSONException {
+ HashMap clickResultHash = new HashMap<>();
HashMap hash = new HashMap<>();
+ HashMap notificationHash = convertNotificationEventToMap(event.getNotification());
+ INotificationClickResult clickResult = event.getResult();
+
+ clickResultHash.put("actionId", clickResult.getActionId());
+ clickResultHash.put("url", clickResult.getUrl());
+
+ hash.put("notification", notificationHash);
+ hash.put("result", clickResultHash);
+
+ return hash;
+ }
- hash.put("androidNotificationId", notification.getAndroidNotificationId());
+ private static HashMap convertNotificationEventToMap(INotification notification) throws JSONException {
+ HashMap notificationHash = new HashMap<>();
+ notificationHash.put("androidNotificationId", notification.getAndroidNotificationId());
if (notification.getGroupedNotifications() != null) {
- hash.put("groupKey", notification.getGroupKey());
- hash.put("groupMessage", notification.getGroupMessage());
- hash.put("groupedNotifications", notification.getGroupedNotifications());
+ notificationHash.put("groupKey", notification.getGroupKey());
+ notificationHash.put("groupMessage", notification.getGroupMessage());
+ notificationHash.put("groupedNotifications", notification.getGroupedNotifications());
}
- hash.put("notificationId", notification.getNotificationId());
- hash.put("title", notification.getTitle());
+ notificationHash.put("notificationId", notification.getNotificationId());
+ notificationHash.put("title", notification.getTitle());
if (notification.getBody() != null)
- hash.put("body", notification.getBody());
+ notificationHash.put("body", notification.getBody());
if (notification.getSmallIcon() != null)
- hash.put("smallIcon", notification.getSmallIcon());
+ notificationHash.put("smallIcon", notification.getSmallIcon());
if (notification.getLargeIcon() != null)
- hash.put("largeIcon", notification.getLargeIcon());
+ notificationHash.put("largeIcon", notification.getLargeIcon());
if (notification.getBigPicture() != null)
- hash.put("bigPicture", notification.getBigPicture());
+ notificationHash.put("bigPicture", notification.getBigPicture());
if (notification.getSmallIconAccentColor() != null)
- hash.put("smallIconAccentColor", notification.getSmallIconAccentColor());
+ notificationHash.put("smallIconAccentColor", notification.getSmallIconAccentColor());
if (notification.getLaunchURL() != null)
- hash.put("launchUrl", notification.getLaunchURL());
+ notificationHash.put("launchUrl", notification.getLaunchURL());
if (notification.getSound() != null)
- hash.put("sound", notification.getSound());
+ notificationHash.put("sound", notification.getSound());
if (notification.getLedColor() != null)
- hash.put("ledColor", notification.getLedColor());
- hash.put("lockScreenVisibility", notification.getLockScreenVisibility());
+ notificationHash.put("ledColor", notification.getLedColor());
+ notificationHash.put("lockScreenVisibility", notification.getLockScreenVisibility());
if (notification.getGroupKey() != null)
- hash.put("groupKey", notification.getGroupKey());
+ notificationHash.put("groupKey", notification.getGroupKey());
if (notification.getGroupMessage() != null)
- hash.put("groupMessage", notification.getGroupMessage());
+ notificationHash.put("groupMessage", notification.getGroupMessage());
if (notification.getFromProjectNumber() != null)
- hash.put("fromProjectNumber", notification.getFromProjectNumber());
+ notificationHash.put("fromProjectNumber", notification.getFromProjectNumber());
if (notification.getCollapseId() != null)
- hash.put("collapseId", notification.getCollapseId());
- hash.put("priority", notification.getPriority());
+ notificationHash.put("collapseId", notification.getCollapseId());
+ notificationHash.put("priority", notification.getPriority());
if (notification.getAdditionalData() != null && notification.getAdditionalData().length() > 0)
- hash.put("additionalData", convertJSONObjectToHashMap(notification.getAdditionalData()));
+ notificationHash.put("additionalData", convertJSONObjectToHashMap(notification.getAdditionalData()));
if (notification.getActionButtons() != null) {
- hash.put("actionButtons", notification.getActionButtons());
+ notificationHash.put("actionButtons", notification.getActionButtons());
}
- hash.put("rawPayload", notification.getRawPayload());
+ notificationHash.put("rawPayload", notification.getRawPayload());
+
+ return notificationHash;
+ }
+
+ private static HashMap convertInAppMessageToMap(IInAppMessage message) {
+ HashMap hash = new HashMap<>();
+ hash.put("messageId", message.getMessageId());
return hash;
}
- public static HashMap convertInAppMessageToMap(IInAppMessage message) {
+ public static HashMap convertInAppMessageWillDisplayEventToMap(IInAppMessageWillDisplayEvent event) {
HashMap hash = new HashMap<>();
+ hash.put("message", convertInAppMessageToMap(event.getMessage()));
- hash.put("messageId", message.getMessageId());
+ return hash;
+ }
+
+ public static HashMap convertInAppMessageDidDisplayEventToMap(IInAppMessageDidDisplayEvent event) {
+ HashMap hash = new HashMap<>();
+ hash.put("message", convertInAppMessageToMap(event.getMessage()));
+
+ return hash;
+ }
+
+ public static HashMap convertInAppMessageWillDismissEventToMap(IInAppMessageWillDismissEvent event) {
+ HashMap hash = new HashMap<>();
+ hash.put("message", convertInAppMessageToMap(event.getMessage()));
return hash;
}
- public static HashMap convertInAppMessageClickResultToMap(IInAppMessageClickResult result) {
+ public static HashMap convertInAppMessageDidDismissEventToMap(IInAppMessageDidDismissEvent event) {
HashMap hash = new HashMap<>();
+ hash.put("message", convertInAppMessageToMap(event.getMessage()));
+
+ return hash;
+ }
+
+ public static HashMap convertInAppMessageClickEventToMap(IInAppMessageClickEvent event) {
+ HashMap resultHash = new HashMap<>();
+ HashMap hash = new HashMap<>();
+ IInAppMessageClickResult result = event.getResult();
+
+ resultHash.put("actionId", result.getActionId());
+ resultHash.put("urlTarget", result.getUrlTarget());
+ resultHash.put("url", result.getUrl());
+ resultHash.put("closingMessage", result.getClosingMessage());
- hash.put("actionId", result.getActionId());
- hash.put("urlTarget", result.getUrlTarget());
- hash.put("url", result.getUrl());
- hash.put("closingMessage", result.getClosingMessage());
+ hash.put("result", resultHash);
+ hash.put("message", convertInAppMessageToMap(event.getMessage()));
return hash;
}
From c544316490d54890e927749723132ce2ee7423a0 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 14 Jul 2023 20:09:46 -0700
Subject: [PATCH 17/29] Update EventManager to allow for multiple Notification
and IAM listeners
Remove set setEventHandler since there can now be multiple listeners
---
src/events/EventManager.ts | 47 ++++++++------------------------------
src/helpers.ts | 15 ------------
2 files changed, 9 insertions(+), 53 deletions(-)
diff --git a/src/events/EventManager.ts b/src/events/EventManager.ts
index 488828d2..3d38581c 100644
--- a/src/events/EventManager.ts
+++ b/src/events/EventManager.ts
@@ -4,7 +4,7 @@ import {
NativeModule,
} from 'react-native';
import NotificationWillDisplayEvent from './NotificationWillDisplayEvent';
-import { isMultipleInstancesPossible } from '../helpers';
+// import { isMultipleInstancesPossible } from '../helpers';
import {
PERMISSION_CHANGED,
SUBSCRIPTION_CHANGED,
@@ -33,14 +33,12 @@ const eventList = [
export default class EventManager {
private RNOneSignal: NativeModule;
private oneSignalEventEmitter: NativeEventEmitter;
- private eventHandlerMap: Map void>;
private eventHandlerArrayMap: Map void>>;
private listeners: { [key: string]: EmitterSubscription };
constructor(RNOneSignal: NativeModule) {
this.RNOneSignal = RNOneSignal;
this.oneSignalEventEmitter = new NativeEventEmitter(RNOneSignal);
- this.eventHandlerMap = new Map(); // used for setters (single replaceable callback)
this.eventHandlerArrayMap = new Map(); // used for adders (multiple callbacks possible)
this.listeners = {};
this.setupListeners();
@@ -58,21 +56,9 @@ export default class EventManager {
// clear handlers
clearHandlers() {
- this.eventHandlerMap = new Map();
this.eventHandlerArrayMap = new Map();
}
- /**
- * Sets the event handler on the JS side of the bridge
- * Supports only one handler at a time
- * @param {string} eventName
- * @param {function} handler
- * @returns void
- */
- setEventHandler(eventName: string, handler: (event: T) => void) {
- this.eventHandlerMap.set(eventName, handler);
- }
-
/**
* Adds the event handler to the corresponding handler array on the JS side of the bridge
* @param {string} eventName
@@ -109,38 +95,23 @@ export default class EventManager {
// returns an event listener with the js to native mapping
generateEventListener(eventName: string): EmitterSubscription {
const addListenerCallback = (payload: Object) => {
- if (isMultipleInstancesPossible(eventName)) {
- // used for adders
- let handlerArray = this.eventHandlerArrayMap.get(eventName);
- if (handlerArray) {
+ let handlerArray = this.eventHandlerArrayMap.get(eventName);
+ if (handlerArray) {
+ if (eventName === NOTIFICATION_WILL_DISPLAY) {
+ handlerArray.forEach((handler) => {
+ handler(new NotificationWillDisplayEvent(payload as OSNotification));
+ });
+ } else {
handlerArray.forEach((handler) => {
handler(payload);
});
}
- } else {
- // used for setters
- let handler = this.eventHandlerMap.get(eventName);
- payload = this.getFinalPayload(eventName, payload);
-
- // Check if we have added listener for this type yet
- if (handler) {
- handler(payload);
- }
}
};
return this.oneSignalEventEmitter.addListener(
- eventName,
+ eventName,
addListenerCallback,
);
}
-
- getFinalPayload(eventName: string, payload: Object): Object {
- switch (eventName) {
- case NOTIFICATION_WILL_DISPLAY:
- return new NotificationWillDisplayEvent(payload as OSNotification);
- default:
- return payload;
- }
- }
}
diff --git a/src/helpers.ts b/src/helpers.ts
index c6dffdbb..d9daf302 100644
--- a/src/helpers.ts
+++ b/src/helpers.ts
@@ -1,6 +1,5 @@
import invariant from 'invariant';
import { NativeModule } from 'react-native';
-import { PERMISSION_CHANGED, SUBSCRIPTION_CHANGED } from './events/events';
export function isValidCallback(handler: Function) {
invariant(typeof handler === 'function', 'Must provide a valid callback');
@@ -17,17 +16,3 @@ export function isNativeModuleLoaded(module: NativeModule): boolean {
return true;
}
-
-/**
- * Returns whether the handler associated with the event name can have multiple instances set
- * @param {String} eventName
- */
-export function isMultipleInstancesPossible(eventName: string) {
- switch (eventName) {
- case PERMISSION_CHANGED:
- case SUBSCRIPTION_CHANGED:
- return true;
- default:
- return false;
- }
-}
From 4f8e60c3433903c84975fc4362627a172d6294fa Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 14 Jul 2023 20:31:58 -0700
Subject: [PATCH 18/29] Fix lint errors
---
src/events/EventManager.ts | 6 ++++--
src/index.ts | 8 +++-----
src/models/Subscription.ts | 4 ++--
3 files changed, 9 insertions(+), 9 deletions(-)
diff --git a/src/events/EventManager.ts b/src/events/EventManager.ts
index 3d38581c..f4b8984b 100644
--- a/src/events/EventManager.ts
+++ b/src/events/EventManager.ts
@@ -99,7 +99,9 @@ export default class EventManager {
if (handlerArray) {
if (eventName === NOTIFICATION_WILL_DISPLAY) {
handlerArray.forEach((handler) => {
- handler(new NotificationWillDisplayEvent(payload as OSNotification));
+ handler(
+ new NotificationWillDisplayEvent(payload as OSNotification),
+ );
});
} else {
handlerArray.forEach((handler) => {
@@ -110,7 +112,7 @@ export default class EventManager {
};
return this.oneSignalEventEmitter.addListener(
- eventName,
+ eventName,
addListenerCallback,
);
}
diff --git a/src/index.ts b/src/index.ts
index 6e1a1f5a..cd82429a 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -21,7 +21,7 @@ import {
import {
PushSubscriptionState,
OSNotificationPermission,
- PushSubscriptionChangedState
+ PushSubscriptionChangedState,
} from './models/Subscription';
import NotificationWillDisplayEvent from './events/NotificationWillDisplayEvent';
import { OutcomeEvent } from './models/Outcomes';
@@ -472,7 +472,7 @@ export namespace OneSignal {
* */
export function permissionNative(): Promise {
if (!isNativeModuleLoaded(RNOneSignal)) {
- return Promise.reject(new Error('OneSignal native module not loaded'));;
+ return Promise.reject(new Error('OneSignal native module not loaded'));
}
if (Platform.OS === 'ios') {
@@ -796,7 +796,5 @@ export {
};
export { default as OSNotification } from './OSNotification';
-export {
- NotificationClickResult,
-} from './models/NotificationEvents';
+export { NotificationClickResult } from './models/NotificationEvents';
export { OSNotificationPermission } from './models/Subscription';
diff --git a/src/models/Subscription.ts b/src/models/Subscription.ts
index 97119cd7..ac21cf24 100644
--- a/src/models/Subscription.ts
+++ b/src/models/Subscription.ts
@@ -13,6 +13,6 @@ export interface PushSubscriptionState {
}
export interface PushSubscriptionChangedState {
- previous: PushSubscriptionState
- current: PushSubscriptionState
+ previous: PushSubscriptionState;
+ current: PushSubscriptionState;
}
From 7c0a465a707619150b25c5f1b88223e2909abe85 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Mon, 17 Jul 2023 11:06:28 -0700
Subject: [PATCH 19/29] remove clearHandlers public method
Additional nit: clean up unused import
---
examples/RNOneSignalTS/src/OSDemo.tsx | 4 ----
src/events/EventManager.ts | 6 ------
src/index.ts | 7 -------
3 files changed, 17 deletions(-)
diff --git a/examples/RNOneSignalTS/src/OSDemo.tsx b/examples/RNOneSignalTS/src/OSDemo.tsx
index 6b9a3dcb..0e4e6451 100644
--- a/examples/RNOneSignalTS/src/OSDemo.tsx
+++ b/examples/RNOneSignalTS/src/OSDemo.tsx
@@ -101,10 +101,6 @@ class OSDemo extends React.Component {
});
}
- componentWillUnmount() {
- OneSignal.clearHandlers();
- }
-
OSLog = (message: string, optionalArg: any = null) => {
if (optionalArg !== null) {
message = message + JSON.stringify(optionalArg);
diff --git a/src/events/EventManager.ts b/src/events/EventManager.ts
index f4b8984b..f4d57465 100644
--- a/src/events/EventManager.ts
+++ b/src/events/EventManager.ts
@@ -4,7 +4,6 @@ import {
NativeModule,
} from 'react-native';
import NotificationWillDisplayEvent from './NotificationWillDisplayEvent';
-// import { isMultipleInstancesPossible } from '../helpers';
import {
PERMISSION_CHANGED,
SUBSCRIPTION_CHANGED,
@@ -54,11 +53,6 @@ export default class EventManager {
}
}
- // clear handlers
- clearHandlers() {
- this.eventHandlerArrayMap = new Map();
- }
-
/**
* Adds the event handler to the corresponding handler array on the JS side of the bridge
* @param {string} eventName
diff --git a/src/index.ts b/src/index.ts
index cd82429a..9c624c95 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -136,13 +136,6 @@ export namespace OneSignal {
}
}
- /** Clears all handlers and observers. */
- export function clearHandlers() {
- if (!isNativeModuleLoaded(RNOneSignal)) return;
-
- eventManager.clearHandlers();
- }
-
export namespace Debug {
/**
* Enable logging to help debug if you run into an issue setting up OneSignal.
From 970f29ea7b3febf529af61e12f41c108da4a5312 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Thu, 20 Jul 2023 17:17:08 -0700
Subject: [PATCH 20/29] Update Event Manager method names
Change clearEventHandler to removeEventListener and EventHandler to EventListener
---
src/events/EventManager.ts | 18 +++++++++---------
src/index.ts | 37 ++++++++++++++++++-------------------
2 files changed, 27 insertions(+), 28 deletions(-)
diff --git a/src/events/EventManager.ts b/src/events/EventManager.ts
index f4d57465..c9e54d91 100644
--- a/src/events/EventManager.ts
+++ b/src/events/EventManager.ts
@@ -32,13 +32,13 @@ const eventList = [
export default class EventManager {
private RNOneSignal: NativeModule;
private oneSignalEventEmitter: NativeEventEmitter;
- private eventHandlerArrayMap: Map void>>;
+ private eventListenerArrayMap: Map void>>;
private listeners: { [key: string]: EmitterSubscription };
constructor(RNOneSignal: NativeModule) {
this.RNOneSignal = RNOneSignal;
this.oneSignalEventEmitter = new NativeEventEmitter(RNOneSignal);
- this.eventHandlerArrayMap = new Map(); // used for adders (multiple callbacks possible)
+ this.eventListenerArrayMap = new Map(); // used for adders (multiple callbacks possible)
this.listeners = {};
this.setupListeners();
}
@@ -59,11 +59,11 @@ export default class EventManager {
* @param {function} handler
* @returns void
*/
- addEventHandler(eventName: string, handler: (event: T) => void) {
- let handlerArray = this.eventHandlerArrayMap.get(eventName);
+ addEventListener(eventName: string, handler: (event: T) => void) {
+ let handlerArray = this.eventListenerArrayMap.get(eventName);
handlerArray && handlerArray.length > 0
? handlerArray.push(handler)
- : this.eventHandlerArrayMap.set(eventName, [handler]);
+ : this.eventListenerArrayMap.set(eventName, [handler]);
}
/**
@@ -72,8 +72,8 @@ export default class EventManager {
* @param {function} handler
* @returns void
*/
- clearEventHandler(eventName: string, handler: any) {
- const handlerArray = this.eventHandlerArrayMap.get(eventName);
+ removeEventListener(eventName: string, handler: any) {
+ const handlerArray = this.eventListenerArrayMap.get(eventName);
if (!handlerArray) {
return;
}
@@ -82,14 +82,14 @@ export default class EventManager {
handlerArray.splice(index, 1);
}
if (handlerArray.length === 0) {
- this.eventHandlerArrayMap.delete(eventName);
+ this.eventListenerArrayMap.delete(eventName);
}
}
// returns an event listener with the js to native mapping
generateEventListener(eventName: string): EmitterSubscription {
const addListenerCallback = (payload: Object) => {
- let handlerArray = this.eventHandlerArrayMap.get(eventName);
+ let handlerArray = this.eventListenerArrayMap.get(eventName);
if (handlerArray) {
if (eventName === NOTIFICATION_WILL_DISPLAY) {
handlerArray.forEach((handler) => {
diff --git a/src/index.ts b/src/index.ts
index 9c624c95..7ddfe5ad 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -207,7 +207,7 @@ export namespace OneSignal {
isValidCallback(listener);
RNOneSignal.addPushSubscriptionObserver();
- eventManager.addEventHandler(
+ eventManager.addEventListener(
SUBSCRIPTION_CHANGED,
listener,
);
@@ -220,7 +220,7 @@ export namespace OneSignal {
) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
- eventManager.clearEventHandler(SUBSCRIPTION_CHANGED, listener);
+ eventManager.removeEventListener(SUBSCRIPTION_CHANGED, listener);
}
/** The readonly push subscription ID */
@@ -488,20 +488,20 @@ export namespace OneSignal {
if (event === 'click') {
RNOneSignal.addNotificationClickListener();
- eventManager.addEventHandler(
+ eventManager.addEventListener(
NOTIFICATION_CLICKED,
listener as (event: NotificationClickEvent) => void,
);
} else if (event === 'foregroundWillDisplay') {
RNOneSignal.addNotificationForegroundLifecycleListener();
- eventManager.addEventHandler(
+ eventManager.addEventListener(
NOTIFICATION_WILL_DISPLAY,
listener as (event: NotificationWillDisplayEvent) => void,
);
} else if (event === 'permissionChange') {
isValidCallback(listener);
RNOneSignal.addPermissionObserver();
- eventManager.addEventHandler(
+ eventManager.addEventListener(
PERMISSION_CHANGED,
listener as (event: boolean) => void,
);
@@ -515,11 +515,11 @@ export namespace OneSignal {
listener: (event: NotificationEventTypeMap[K]) => void,
): void {
if (event === 'click') {
- eventManager.clearEventHandler(NOTIFICATION_CLICKED, listener);
+ eventManager.removeEventListener(NOTIFICATION_CLICKED, listener);
} else if (event === 'foregroundWillDisplay') {
- eventManager.clearEventHandler(NOTIFICATION_WILL_DISPLAY, listener);
+ eventManager.removeEventListener(NOTIFICATION_WILL_DISPLAY, listener);
} else if (event === 'permissionChange') {
- eventManager.clearEventHandler(PERMISSION_CHANGED, listener);
+ eventManager.removeEventListener(PERMISSION_CHANGED, listener);
} else {
return;
}
@@ -527,7 +527,6 @@ export namespace OneSignal {
/**
* Removes all OneSignal notifications.
- * Android Only. iOS provides a standard way to clear notifications by clearing badge count.
*/
export function clearAll() {
if (!isNativeModuleLoaded(RNOneSignal)) return;
@@ -584,32 +583,32 @@ export namespace OneSignal {
if (event === 'click') {
isValidCallback(listener);
RNOneSignal.addInAppMessageClickListener();
- eventManager.addEventHandler(
+ eventManager.addEventListener(
IN_APP_MESSAGE_CLICKED,
listener as (event: InAppMessageClickEvent) => void,
);
} else {
if (event === 'willDisplay') {
isValidCallback(listener);
- eventManager.addEventHandler(
+ eventManager.addEventListener(
IN_APP_MESSAGE_WILL_DISPLAY,
listener as (event: InAppMessageWillDisplayEvent) => void,
);
} else if (event === 'didDisplay') {
isValidCallback(listener);
- eventManager.addEventHandler(
+ eventManager.addEventListener(
IN_APP_MESSAGE_DID_DISPLAY,
listener as (event: InAppMessageDidDisplayEvent) => void,
);
} else if (event === 'willDismiss') {
isValidCallback(listener);
- eventManager.addEventHandler(
+ eventManager.addEventListener(
IN_APP_MESSAGE_WILL_DISMISS,
listener as (event: InAppMessageWillDismissEvent) => void,
);
} else if (event === 'didDismiss') {
isValidCallback(listener);
- eventManager.addEventHandler(
+ eventManager.addEventListener(
IN_APP_MESSAGE_DID_DISMISS,
listener as (event: InAppMessageDidDismissEvent) => void,
);
@@ -628,16 +627,16 @@ export namespace OneSignal {
listener: (obj: InAppMessageEventTypeMap[K]) => void,
): void {
if (event === 'click') {
- eventManager.clearEventHandler(IN_APP_MESSAGE_CLICKED, listener);
+ eventManager.removeEventListener(IN_APP_MESSAGE_CLICKED, listener);
} else {
if (event === 'willDisplay') {
- eventManager.clearEventHandler(IN_APP_MESSAGE_WILL_DISPLAY, listener);
+ eventManager.removeEventListener(IN_APP_MESSAGE_WILL_DISPLAY, listener);
} else if (event === 'didDisplay') {
- eventManager.clearEventHandler(IN_APP_MESSAGE_DID_DISPLAY, listener);
+ eventManager.removeEventListener(IN_APP_MESSAGE_DID_DISPLAY, listener);
} else if (event === 'willDismiss') {
- eventManager.clearEventHandler(IN_APP_MESSAGE_WILL_DISMISS, listener);
+ eventManager.removeEventListener(IN_APP_MESSAGE_WILL_DISMISS, listener);
} else if (event === 'didDismiss') {
- eventManager.clearEventHandler(IN_APP_MESSAGE_DID_DISMISS, listener);
+ eventManager.removeEventListener(IN_APP_MESSAGE_DID_DISMISS, listener);
} else {
return;
}
From 5515e81d8f8d6389f1a95774a15b2120774b5ef6 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Thu, 20 Jul 2023 17:27:01 -0700
Subject: [PATCH 21/29] remove setLaunchURLsInApp
---
MIGRATION_GUIDE.md | 3 +--
ios/RCTOneSignal/RCTOneSignalEventEmitter.m | 4 ----
src/index.ts | 13 -------------
3 files changed, 1 insertion(+), 19 deletions(-)
diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md
index 2605f2c6..4bee1118 100644
--- a/MIGRATION_GUIDE.md
+++ b/MIGRATION_GUIDE.md
@@ -146,8 +146,7 @@ The SDK is still accessible via a `OneSignal` static class. It provides access t
| `OneSignal.User.login("USER_EXTERNAL_ID")` | _Login to OneSignal under the user identified by the [externalId] provided. The act of logging a user into the OneSignal SDK will switch the [user] context to that specific user.
- If the [externalId] exists, the user will be retrieved and the context will be set from that user information. If operations have already been performed under a device-scoped user, they **_will not_** be applied to the now logged in user (they will be lost). - If the [externalId] does not exist the user, the user will be created and the context set from the current local state. If operations have already been performed under a device-scoped user, those operations **_will_** be applied to the newly created user.
**_Push Notifications and In App Messaging_** Logging in a new user will automatically transfer the push notification and in app messaging subscription from the current user (if there is one) to the newly logged in user. This is because both push notifications and in-app messages are owned by the device._ |
| `OneSignal.User.logout()` | _Logout the user previously logged in via [login]. The [user] property now references a new device-scoped user. A device-scoped user has no user identity that can later be retrieved, except through this device as long as the app remains installed and the app data is not cleared._ |
| `OneSignal.setConsentGiven(true)` | _Indicates whether privacy consent has been granted. This field is only relevant when the application has opted into data privacy protections. See [requiresPrivacyConsent]._ |
-| `OneSignal.setConsentRequired(true)` | _Determines whether a user must consent to privacy prior to their user data being sent up to OneSignal. This should be set to `true` prior to the invocation of `initialize` to ensure compliance._ |
-| `OneSignal.setLaunchURLsInApp(true)` | _This method can be used to set if launch URLs should be opened in safari or within the application. Set to `true` to launch all notifications with a URL in the app instead of the default web browser. Make sure to call `setLaunchURLsInApp` before the `initialize` call._ |
+| `OneSignal.setConsentRequired(true)` | _Determines whether a user must consent to privacy prior to their user data being sent up to OneSignal. This should be set to `true` prior to the invocation of `initialize` to ensure compliance._
## Live Activities Namespace
diff --git a/ios/RCTOneSignal/RCTOneSignalEventEmitter.m b/ios/RCTOneSignal/RCTOneSignalEventEmitter.m
index 7d56dec6..61dd6701 100644
--- a/ios/RCTOneSignal/RCTOneSignalEventEmitter.m
+++ b/ios/RCTOneSignal/RCTOneSignalEventEmitter.m
@@ -102,10 +102,6 @@ + (void)sendEventWithName:(NSString *)name withBody:(NSDictionary *)body {
[OneSignal initialize:appId withLaunchOptions:NULL];
}
-RCT_EXPORT_METHOD(setLaunchURLsInApp:(BOOL)isEnabled) {
- [OneSignal setLaunchURLsInApp:isEnabled];
-}
-
RCT_EXPORT_METHOD(login:(NSString *)externalId) {
[OneSignal login:externalId];
}
diff --git a/src/index.ts b/src/index.ts
index 7ddfe5ad..20a92471 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -123,19 +123,6 @@ export namespace OneSignal {
RNOneSignal.setPrivacyConsentGiven(granted);
}
- /** This method can be used to set if launch URLs should be opened in safari or within the application. */
- export function setLaunchURLsInApp(isEnabled: boolean) {
- if (!isNativeModuleLoaded(RNOneSignal)) return;
-
- if (Platform.OS === 'ios') {
- RNOneSignal.setLaunchURLsInApp(isEnabled);
- } else {
- console.log(
- 'setLaunchURLsInApp: this function is not supported on Android',
- );
- }
- }
-
export namespace Debug {
/**
* Enable logging to help debug if you run into an issue setting up OneSignal.
From f3b2aa5b3013cb87ccae6ccb0d07e5105194873d Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Thu, 20 Jul 2023 17:31:09 -0700
Subject: [PATCH 22/29] Add back clearAll method to iOS
---
ios/RCTOneSignal/RCTOneSignalEventEmitter.m | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/ios/RCTOneSignal/RCTOneSignalEventEmitter.m b/ios/RCTOneSignal/RCTOneSignalEventEmitter.m
index 61dd6701..1e459ae1 100644
--- a/ios/RCTOneSignal/RCTOneSignalEventEmitter.m
+++ b/ios/RCTOneSignal/RCTOneSignalEventEmitter.m
@@ -289,6 +289,10 @@ + (void)sendEventWithName:(NSString *)name withBody:(NSDictionary *)body {
[event preventDefault];
}
+RCT_EXPORT_METHOD(clearAllNotifications) {
+ [OneSignal.Notifications clearAll];
+}
+
// OneSignal.Session namespace methods
RCT_EXPORT_METHOD(addOutcome:(NSString *)name) {
[OneSignal.Session addOutcome:name];
From e4ab46ce213d6b407c90d401f38ca666549902cc Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Thu, 20 Jul 2023 17:34:01 -0700
Subject: [PATCH 23/29] Update Android notification and push subscription
conversion methods naming/routing
---
.../rnonesignalandroid/RNOneSignal.java | 12 ++++--------
.../geektime/rnonesignalandroid/RNUtils.java | 18 ++++++++++--------
2 files changed, 14 insertions(+), 16 deletions(-)
diff --git a/android/src/main/java/com/geektime/rnonesignalandroid/RNOneSignal.java b/android/src/main/java/com/geektime/rnonesignalandroid/RNOneSignal.java
index 460de719..ae80606f 100644
--- a/android/src/main/java/com/geektime/rnonesignalandroid/RNOneSignal.java
+++ b/android/src/main/java/com/geektime/rnonesignalandroid/RNOneSignal.java
@@ -351,14 +351,15 @@ public void onWillDisplay(INotificationWillDisplayEvent event) {
event.getNotification().display();
}
- String notificationId = event.getNotification().getNotificationId();
+ INotification notification = event.getNotification();
+ String notificationId = notification.getNotificationId();
notificationWillDisplayCache.put(notificationId, (INotificationWillDisplayEvent) event);
event.preventDefault();
try {
sendEvent("OneSignal-notificationWillDisplayInForeground",
RNUtils.convertHashMapToWritableMap(
- RNUtils.convertNotificationEventToMap(event)));
+ RNUtils.convertNotificationToMap(notification)));
try {
synchronized (event) {
@@ -495,15 +496,10 @@ public void addPushSubscriptionObserver() {
@Override
public void onPushSubscriptionChange(PushSubscriptionChangedState pushSubscriptionChangedState) {
- PushSubscriptionState pushSubscription = pushSubscriptionChangedState.getCurrent();
- if (!(pushSubscription instanceof PushSubscriptionState)){
- return;
- }
-
try {
sendEvent("OneSignal-subscriptionChanged",
RNUtils.convertHashMapToWritableMap(
- RNUtils.convertOnSubscriptionChangedToMap(pushSubscription)));
+ RNUtils.convertPushSubscriptionChangedStateToMap(pushSubscriptionChangedState)));
Log.i("OneSignal", "sending subscription change event");
} catch (JSONException e) {
e.printStackTrace();
diff --git a/android/src/main/java/com/geektime/rnonesignalandroid/RNUtils.java b/android/src/main/java/com/geektime/rnonesignalandroid/RNUtils.java
index 511145e4..ca5e7999 100644
--- a/android/src/main/java/com/geektime/rnonesignalandroid/RNUtils.java
+++ b/android/src/main/java/com/geektime/rnonesignalandroid/RNUtils.java
@@ -64,12 +64,6 @@ public static WritableMap convertHashMapToWritableMap(HashMap ha
return writableMap;
}
- public static HashMap convertNotificationWillDisplayEventToMap(INotificationWillDisplayEvent event) throws JSONException {
- HashMap notificationHash = convertNotificationEventToMap(event.getNotification());
-
- return notificationHash;
- }
-
public static HashMap convertNotificationClickEventToMap(INotificationClickEvent event) throws JSONException {
HashMap clickResultHash = new HashMap<>();
HashMap hash = new HashMap<>();
@@ -85,7 +79,7 @@ public static HashMap convertNotificationClickEventToMap(INotifi
return hash;
}
- private static HashMap convertNotificationEventToMap(INotification notification) throws JSONException {
+ private static HashMap convertNotificationToMap(INotification notification) throws JSONException {
HashMap notificationHash = new HashMap<>();
notificationHash.put("androidNotificationId", notification.getAndroidNotificationId());
@@ -185,7 +179,7 @@ public static HashMap convertInAppMessageClickEventToMap(IInAppM
return hash;
}
- public static HashMap convertOnSubscriptionChangedToMap(PushSubscriptionState state) {
+ public static HashMap convertPushSubscriptionStateToMap(PushSubscriptionState state) {
HashMap hash = new HashMap<>();
hash.put("token", state.getToken());
@@ -195,6 +189,14 @@ public static HashMap convertOnSubscriptionChangedToMap(PushSubs
return hash;
}
+ public static HashMap convertPushSubscriptionChangedStateToMap(PushSubscriptionChangedState state) {
+ HashMap hash = new HashMap<>();
+ hash.put("current", convertPushSubscriptionStateToMap(state.getCurrent()));
+ hash.put("previous", convertPushSubscriptionStateToMap(state.getPrevious()));
+
+ return hash;
+ }
+
public static HashMap convertJSONObjectToHashMap(JSONObject object) throws JSONException {
HashMap hash = new HashMap<>();
From 07b9803c27ab97b758c6d221352d7356692e2951 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Thu, 20 Jul 2023 17:35:00 -0700
Subject: [PATCH 24/29] Remove user state refresh limitation from Migration
Guide
---
MIGRATION_GUIDE.md | 1 -
1 file changed, 1 deletion(-)
diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md
index 4bee1118..5f3809df 100644
--- a/MIGRATION_GUIDE.md
+++ b/MIGRATION_GUIDE.md
@@ -377,7 +377,6 @@ The Debug namespace is accessible via `OneSignal.Debug` and provide access to de
- This is a Beta release so please test thorougly prior to production use.
- Changing app IDs is not supported.
- Any `User` namespace calls must be invoked **after** initialization. Example: `OneSignal.User.addTag("tag", "2")`
-- In the iOS SDK, the user state is only refreshed from the server when a new session is started (cold start or backgrounded for over 30 seconds) or when the user is logged in. This is by design.
# Known issues
From d8099e1718e913fc0f5da19c19740555eeb2f928 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Thu, 20 Jul 2023 17:51:55 -0700
Subject: [PATCH 25/29] Update import for push subscription changed state and
method declarations for notification click
---
.../main/java/com/geektime/rnonesignalandroid/RNUtils.java | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/android/src/main/java/com/geektime/rnonesignalandroid/RNUtils.java b/android/src/main/java/com/geektime/rnonesignalandroid/RNUtils.java
index ca5e7999..0de8c612 100644
--- a/android/src/main/java/com/geektime/rnonesignalandroid/RNUtils.java
+++ b/android/src/main/java/com/geektime/rnonesignalandroid/RNUtils.java
@@ -26,6 +26,7 @@
import com.onesignal.notifications.INotificationReceivedEvent;
import com.onesignal.user.subscriptions.IPushSubscription;
import com.onesignal.user.subscriptions.PushSubscriptionState;
+import com.onesignal.user.subscriptions.PushSubscriptionChangedState;
import org.json.JSONArray;
import org.json.JSONException;
@@ -67,7 +68,7 @@ public static WritableMap convertHashMapToWritableMap(HashMap ha
public static HashMap convertNotificationClickEventToMap(INotificationClickEvent event) throws JSONException {
HashMap clickResultHash = new HashMap<>();
HashMap hash = new HashMap<>();
- HashMap notificationHash = convertNotificationEventToMap(event.getNotification());
+ HashMap notificationHash = convertNotificationToMap(event.getNotification());
INotificationClickResult clickResult = event.getResult();
clickResultHash.put("actionId", clickResult.getActionId());
@@ -79,7 +80,7 @@ public static HashMap convertNotificationClickEventToMap(INotifi
return hash;
}
- private static HashMap convertNotificationToMap(INotification notification) throws JSONException {
+ public static HashMap convertNotificationToMap(INotification notification) throws JSONException {
HashMap notificationHash = new HashMap<>();
notificationHash.put("androidNotificationId", notification.getAndroidNotificationId());
From d5d21f32ba6b6896aaacb4ba261ace9014f0d12d Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 21 Jul 2023 14:41:53 -0700
Subject: [PATCH 26/29] Replace logLevel types from int to enum
---
examples/RNOneSignalTS/src/OSDemo.tsx | 4 ++--
src/index.ts | 12 ++++++++++--
2 files changed, 12 insertions(+), 4 deletions(-)
diff --git a/examples/RNOneSignalTS/src/OSDemo.tsx b/examples/RNOneSignalTS/src/OSDemo.tsx
index 0e4e6451..4c367fe2 100644
--- a/examples/RNOneSignalTS/src/OSDemo.tsx
+++ b/examples/RNOneSignalTS/src/OSDemo.tsx
@@ -1,4 +1,4 @@
-import {OneSignal} from 'react-native-onesignal';
+import {LogLevel, OneSignal} from 'react-native-onesignal';
import * as React from 'react';
import {Alert, StyleSheet, View, ScrollView, SafeAreaView} from 'react-native';
import OSButtons from './OSButtons';
@@ -31,7 +31,7 @@ class OSDemo extends React.Component {
async componentDidMount() {
OneSignal.initialize(APP_ID);
- OneSignal.Debug.setLogLevel(6);
+ OneSignal.Debug.setLogLevel(LogLevel.Verbose);
OneSignal.Notifications.addEventListener(
'foregroundWillDisplay',
diff --git a/src/index.ts b/src/index.ts
index 20a92471..d4acd159 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -40,8 +40,16 @@ import { isValidCallback, isNativeModuleLoaded } from './helpers';
const RNOneSignal = NativeModules.OneSignal;
const eventManager = new EventManager(RNOneSignal);
-// 0 = None, 1 = Fatal, 2 = Errors, 3 = Warnings, 4 = Info, 5 = Debug, 6 = Verbose
-export type LogLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6;
+/// An enum that declares different types of log levels you can use with the OneSignal SDK, going from the least verbose (none) to verbose (print all comments).
+export enum LogLevel {
+ None,
+ Fatal,
+ Error,
+ Warn,
+ Info,
+ Debug,
+ Verbose,
+}
// Internal wrapper notification permission state that is being updated by the permission change handler.
let notificationPermission = false;
From 117722b0b6bde22d3dd13e5980602e222fe96225 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 21 Jul 2023 14:54:38 -0700
Subject: [PATCH 27/29] Bump iOS native dependency to beta-5
---
react-native-onesignal.podspec | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/react-native-onesignal.podspec b/react-native-onesignal.podspec
index 248b431b..64a33462 100644
--- a/react-native-onesignal.podspec
+++ b/react-native-onesignal.podspec
@@ -22,5 +22,5 @@ Pod::Spec.new do |s|
# pod 'React', :path => '../node_modules/react-native/'
# The Native OneSignal-iOS-SDK XCFramework from cocoapods.
- s.dependency 'OneSignalXCFramework', '5.0.0-beta-04'
+ s.dependency 'OneSignalXCFramework', '5.0.0-beta-05'
end
From 8568b1ef29ea87eab3665dbad9d2d702fa55b30c Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 21 Jul 2023 14:59:10 -0700
Subject: [PATCH 28/29] Update InAppMessage lifecycle listeners to send entire
event on iOS
---
ios/RCTOneSignal/RCTOneSignal.m | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/ios/RCTOneSignal/RCTOneSignal.m b/ios/RCTOneSignal/RCTOneSignal.m
index 004a9dc6..948dc5d4 100644
--- a/ios/RCTOneSignal/RCTOneSignal.m
+++ b/ios/RCTOneSignal/RCTOneSignal.m
@@ -91,19 +91,19 @@ - (void)onClickInAppMessage:(OSInAppMessageClickEvent * _Nonnull)event {
}
- (void)onWillDisplayInAppMessage:(OSInAppMessageWillDisplayEvent * _Nonnull)event {
- [self sendEvent:OSEventString(InAppMessageWillDisplay) withBody:@{@"message": [event.message jsonRepresentation]}];
+ [self sendEvent:OSEventString(InAppMessageWillDisplay) withBody:[event jsonRepresentation]];
}
- (void)onDidDisplayInAppMessage:(OSInAppMessageDidDisplayEvent * _Nonnull)event {
- [self sendEvent:OSEventString(InAppMessageDidDisplay) withBody:@{@"message": [event.message jsonRepresentation]}];
+ [self sendEvent:OSEventString(InAppMessageDidDisplay) withBody:[event jsonRepresentation]];
}
- (void)onWillDismissInAppMessage:(OSInAppMessageWillDismissEvent * _Nonnull)event {
- [self sendEvent:OSEventString(InAppMessageWillDismiss) withBody:@{@"message": [event.message jsonRepresentation]}];
+ [self sendEvent:OSEventString(InAppMessageWillDismiss) withBody:[event jsonRepresentation]];
}
- (void)onDidDismissInAppMessage:(OSInAppMessageDidDismissEvent * _Nonnull)event {
- [self sendEvent:OSEventString(InAppMessageDidDismiss) withBody:@{@"message": [event.message jsonRepresentation]}];
+ [self sendEvent:OSEventString(InAppMessageDidDismiss) withBody:[event jsonRepresentation]];
}
- (void)dealloc {
From 980b45834077357a3e31400ba9c11b65ddad51d4 Mon Sep 17 00:00:00 2001
From: Jenna Antilla <46546946+jennantilla@users.noreply.github.com>
Date: Fri, 21 Jul 2023 15:05:13 -0700
Subject: [PATCH 29/29] Fix linting errors
---
src/index.ts | 20 ++++++++++++++++----
1 file changed, 16 insertions(+), 4 deletions(-)
diff --git a/src/index.ts b/src/index.ts
index d4acd159..b3ef34bb 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -625,13 +625,25 @@ export namespace OneSignal {
eventManager.removeEventListener(IN_APP_MESSAGE_CLICKED, listener);
} else {
if (event === 'willDisplay') {
- eventManager.removeEventListener(IN_APP_MESSAGE_WILL_DISPLAY, listener);
+ eventManager.removeEventListener(
+ IN_APP_MESSAGE_WILL_DISPLAY,
+ listener,
+ );
} else if (event === 'didDisplay') {
- eventManager.removeEventListener(IN_APP_MESSAGE_DID_DISPLAY, listener);
+ eventManager.removeEventListener(
+ IN_APP_MESSAGE_DID_DISPLAY,
+ listener,
+ );
} else if (event === 'willDismiss') {
- eventManager.removeEventListener(IN_APP_MESSAGE_WILL_DISMISS, listener);
+ eventManager.removeEventListener(
+ IN_APP_MESSAGE_WILL_DISMISS,
+ listener,
+ );
} else if (event === 'didDismiss') {
- eventManager.removeEventListener(IN_APP_MESSAGE_DID_DISMISS, listener);
+ eventManager.removeEventListener(
+ IN_APP_MESSAGE_DID_DISMISS,
+ listener,
+ );
} else {
return;
}