├── .gitignore
├── LICENSE
├── PushyRN.podspec
├── README.md
├── android
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── me
│ └── pushy
│ └── sdk
│ └── react
│ ├── PushyPackage.java
│ ├── config
│ ├── PushyHeadlessJSConfig.java
│ └── PushyIntentExtras.java
│ ├── modules
│ └── PushyModule.java
│ ├── receivers
│ └── PushReceiver.java
│ ├── services
│ └── PushyNotificationService.java
│ └── util
│ ├── PushyMapUtils.java
│ └── PushyPersistence.java
├── ios
├── PushyModule.h
├── PushyModule.m
└── PushyRN.xcodeproj
│ ├── project.pbxproj
│ └── project.xcworkspace
│ └── contents.xcworkspacedata
├── lib
├── Pushy.d.ts
└── Pushy.js
└── package.json
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | xcuserdata/
3 | *.xcuserstate
4 | IDEWorkspaceChecks.plist
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/PushyRN.podspec:
--------------------------------------------------------------------------------
1 | require 'json'
2 |
3 | package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
4 |
5 | Pod::Spec.new do |s|
6 | s.name = 'PushyRN'
7 | s.version = package['version']
8 | s.summary = package['description']
9 | s.homepage = package['homepage']
10 |
11 | s.author = package['author']
12 | s.license = package['license']
13 |
14 | s.platform = :ios, "9.0"
15 | s.source = { :git => 'https://github.com/pushy/pushy-react-native.git', :tag => s.version }
16 | s.source_files = '**/*.{h,c,m,swift}'
17 | s.requires_arc = true
18 | s.swift_version = '4.2'
19 |
20 | # The "React" pod is required due to the use of RCTBridgeModule & RCTEventEmitter
21 | # Let's ensure we have version 0.13.0 or greater to avoid a cocoapods issue noted in React Native's release notes:
22 | # https://github.com/facebook/react-native/releases/tag/v0.13.0
23 | s.dependency 'React', '>= 0.13.0', '< 1.0.0'
24 |
25 | # Pushy iOS SDK
26 | s.dependency 'Pushy', '1.0.59'
27 | end
28 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # pushy-react-native
2 | [](https://www.npmjs.com/package/pushy-react-native)
3 |
4 | The official [Pushy SDK](https://pushy.me/) for [React Native](https://facebook.github.io/react-native/) apps.
5 |
6 | > [Pushy](https://pushy.me/) is the most reliable push notification gateway, perfect for real-time, mission-critical applications.
7 |
8 | ## Usage
9 |
10 | Please refer to our [detailed documentation](https://pushy.me/docs/additional-platforms/react-native) to get started.
11 |
12 | ## Demo
13 |
14 | Please refer to [pushy-demo-react-native](https://github.com/pushy/pushy-demo-react-native) for a sample project that integrates this SDK.
15 |
16 | ## License
17 |
18 | [Apache 2.0](LICENSE)
19 |
--------------------------------------------------------------------------------
/android/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion rootProject.ext.compileSdkVersion
5 | namespace "me.pushy.sdk.react"
6 |
7 | defaultConfig {
8 | consumerProguardFiles 'proguard-rules.pro'
9 | minSdkVersion rootProject.ext.minSdkVersion
10 | targetSdkVersion rootProject.ext.targetSdkVersion
11 | }
12 | }
13 |
14 | dependencies {
15 | implementation "com.facebook.react:react-native:+"
16 |
17 | // Pushy SDK for Android
18 | implementation 'me.pushy:sdk:1.0.121'
19 | }
20 |
--------------------------------------------------------------------------------
/android/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Pushy ProGuard Rules
2 | -dontwarn me.pushy.**
3 | -keep class me.pushy.** { *; }
4 | -keep class androidx.core.app.** { *; }
5 | -keep class android.support.v4.app.** { *; }
--------------------------------------------------------------------------------
/android/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
51 |
52 |
53 |
54 |
55 |
--------------------------------------------------------------------------------
/android/src/main/java/me/pushy/sdk/react/PushyPackage.java:
--------------------------------------------------------------------------------
1 | package me.pushy.sdk.react;
2 |
3 | import com.facebook.react.bridge.NativeModule;
4 | import com.facebook.react.bridge.ReactApplicationContext;
5 |
6 | import com.facebook.react.ReactPackage;
7 | import com.facebook.react.uimanager.ViewManager;
8 |
9 | import java.util.ArrayList;
10 | import java.util.Collections;
11 | import java.util.List;
12 |
13 | import me.pushy.sdk.react.modules.PushyModule;
14 |
15 | public class PushyPackage implements ReactPackage {
16 | @Override
17 | public List createViewManagers(ReactApplicationContext reactContext) {
18 | return Collections.emptyList();
19 | }
20 |
21 | @Override
22 | public List createNativeModules(ReactApplicationContext reactContext) {
23 | List modules = new ArrayList<>();
24 |
25 | // Add the Pushy module
26 | modules.add(new PushyModule(reactContext));
27 |
28 | // We're done here
29 | return modules;
30 | }
31 | }
--------------------------------------------------------------------------------
/android/src/main/java/me/pushy/sdk/react/config/PushyHeadlessJSConfig.java:
--------------------------------------------------------------------------------
1 | package me.pushy.sdk.react.config;
2 |
3 | public class PushyHeadlessJSConfig {
4 | public static final String PUSH_RECEIVER_HEADLESS_TASK_NAME = "PushyPushReceiver";
5 | public static final boolean PUSH_RECEIVER_HEADLESS_TASK_FOREGROUND = true;
6 | }
7 |
8 |
--------------------------------------------------------------------------------
/android/src/main/java/me/pushy/sdk/react/config/PushyIntentExtras.java:
--------------------------------------------------------------------------------
1 | package me.pushy.sdk.react.config;
2 |
3 | public class PushyIntentExtras {
4 | public static final String NOTIFICATION_CLICKED = "_pushyNotificationClicked";
5 | public static final String NOTIFICATION_PAYLOAD = "_pushyNotificationPayload";
6 | }
7 |
--------------------------------------------------------------------------------
/android/src/main/java/me/pushy/sdk/react/modules/PushyModule.java:
--------------------------------------------------------------------------------
1 | package me.pushy.sdk.react.modules;
2 |
3 | import android.app.Activity;
4 | import android.app.Notification;
5 | import android.app.NotificationManager;
6 | import android.app.PendingIntent;
7 | import android.content.Context;
8 | import android.content.Intent;
9 | import android.content.res.Resources;
10 | import android.media.RingtoneManager;
11 | import android.os.AsyncTask;
12 |
13 | import com.facebook.react.bridge.ActivityEventListener;
14 | import com.facebook.react.bridge.Promise;
15 | import com.facebook.react.bridge.ReactApplicationContext;
16 | import com.facebook.react.bridge.ReactContextBaseJavaModule;
17 | import com.facebook.react.bridge.ReactMethod;
18 | import com.facebook.react.bridge.ReadableMap;
19 | import com.facebook.react.bridge.WritableMap;
20 | import com.facebook.react.modules.core.DeviceEventManagerModule;
21 |
22 | import org.json.JSONObject;
23 |
24 | import me.pushy.sdk.Pushy;
25 | import me.pushy.sdk.react.config.PushyIntentExtras;
26 | import me.pushy.sdk.react.util.PushyMapUtils;
27 | import me.pushy.sdk.react.util.PushyPersistence;
28 | import me.pushy.sdk.util.PushyLogger;
29 | import me.pushy.sdk.util.PushyStringUtils;
30 | import me.pushy.sdk.util.exceptions.PushyException;
31 |
32 | public class PushyModule extends ReactContextBaseJavaModule implements ActivityEventListener {
33 | public PushyModule(ReactApplicationContext reactContext) {
34 | super(reactContext);
35 |
36 | // Hook into activity events (onNewIntent)
37 | reactContext.addActivityEventListener(this);
38 | }
39 |
40 | @Override
41 | public String getName() {
42 | return "PushyModule";
43 | }
44 |
45 | @ReactMethod
46 | public void notify(String title, String text, ReadableMap payload) {
47 | // Cache app context
48 | Context context = getReactApplicationContext();
49 |
50 | // Prepare a notification with vibration, sound and lights
51 | Notification.Builder builder = new Notification.Builder(context)
52 | .setSmallIcon(getNotificationIcon(context))
53 | .setContentTitle(title)
54 | .setContentText(text)
55 | .setAutoCancel(true)
56 | .setVibrate(new long[]{0, 400, 250, 400})
57 | .setContentIntent(getMainActivityPendingIntent(context, payload))
58 | .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
59 |
60 | // Get an instance of the NotificationManager service
61 | NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
62 |
63 | // Automatically configure a Notification Channel for devices running Android O+
64 | Pushy.setNotificationChannel(builder, context);
65 |
66 | // Build the notification and display it
67 | notificationManager.notify(text.hashCode(), builder.build());
68 | }
69 |
70 | @ReactMethod
71 | public void register(final Promise promise) {
72 | // Run network I/O in background thread
73 | AsyncTask.execute(new Runnable() {
74 | @Override
75 | public void run() {
76 | try {
77 | // Assign a unique token to this device
78 | String deviceToken = Pushy.register(getCurrentActivity() != null ? getCurrentActivity() : getReactApplicationContext());
79 |
80 | // Resolve the promise with the token
81 | promise.resolve(deviceToken);
82 | }
83 | catch (PushyException exc) {
84 | // Reject the promise with the exception
85 | promise.reject(exc);
86 | }
87 | }
88 | });
89 | }
90 |
91 | @ReactMethod
92 | public void hideNotifications() {
93 | // Get an instance of the NotificationManager service
94 | NotificationManager notificationManager = (NotificationManager) getReactApplicationContext().getSystemService(getReactApplicationContext().NOTIFICATION_SERVICE);
95 |
96 | // Cancel all visible notifications
97 | notificationManager.cancelAll();
98 | }
99 |
100 | @ReactMethod
101 | public void listen() {
102 | // Call Pushy.listen() to establish a connection
103 | Pushy.listen(getReactApplicationContext());
104 |
105 | // If no intent, no notification clicked
106 | if (getReactApplicationContext() == null || getReactApplicationContext().getCurrentActivity() == null || getReactApplicationContext().getCurrentActivity().getIntent() == null) {
107 | return;
108 | }
109 |
110 | // Check whether activity was instantiated from notification
111 | onNotificationClicked(getReactApplicationContext().getCurrentActivity().getIntent());
112 | }
113 |
114 | @ReactMethod
115 | public void unregister() {
116 | // Unregister the device from receiving notifications
117 | Pushy.unregister(getReactApplicationContext());
118 | }
119 |
120 | @ReactMethod
121 | public void subscribe(final String topic, final Promise promise) {
122 | // Run network I/O in background thread
123 | AsyncTask.execute(new Runnable() {
124 | @Override
125 | public void run() {
126 | try {
127 | // Attempt to subscribe the device to topic
128 | Pushy.subscribe(topic, getReactApplicationContext());
129 |
130 | // Resolve the promise with success
131 | promise.resolve(true);
132 | }
133 | catch (PushyException exc) {
134 | // Reject the promise with the exception
135 | promise.reject(exc);
136 | }
137 | }
138 | });
139 | }
140 |
141 | @ReactMethod
142 | public void unsubscribe(final String topic, final Promise promise) {
143 | // Run network I/O in background thread
144 | AsyncTask.execute(new Runnable() {
145 | @Override
146 | public void run() {
147 | try {
148 | // Attempt to unsubscribe the device from topic
149 | Pushy.unsubscribe(topic, getReactApplicationContext());
150 |
151 | // Resolve the promise with success
152 | promise.resolve(true);
153 | }
154 | catch (PushyException exc) {
155 | // Reject the promise with the exception
156 | promise.reject(exc);
157 | }
158 | }
159 | });
160 | }
161 |
162 | @ReactMethod
163 | public void setAppId(String appId) {
164 | Pushy.setAppId(appId, getReactApplicationContext());
165 | }
166 |
167 | @ReactMethod
168 | public void togglePermissionVerification(boolean value) {
169 | Pushy.togglePermissionVerification(value, getReactApplicationContext());
170 | }
171 |
172 | @ReactMethod
173 | public void toggleDirectConnectivity(boolean value) {
174 | Pushy.toggleDirectConnectivity(value, getReactApplicationContext());
175 | }
176 |
177 | @ReactMethod
178 | public void toggleForegroundService(boolean value) {
179 | Pushy.toggleForegroundService(value, getReactApplicationContext());
180 | }
181 |
182 | @ReactMethod
183 | public void toggleNotifications(boolean value) {
184 | Pushy.toggleNotifications(value, getReactApplicationContext());
185 | }
186 |
187 | @ReactMethod
188 | public void setHeartbeatInterval(int seconds) {
189 | Pushy.setHeartbeatInterval(seconds, getReactApplicationContext());
190 | }
191 |
192 | @ReactMethod
193 | public void setJobServiceInterval(int seconds) {
194 | Pushy.setJobServiceInterval(seconds, getReactApplicationContext());
195 | }
196 |
197 | @ReactMethod
198 | public void setEnterpriseConfig(String apiEndpoint, String mqttEndpoint) {
199 | Pushy.setEnterpriseConfig(apiEndpoint, mqttEndpoint, getReactApplicationContext());
200 | }
201 |
202 | @ReactMethod
203 | public void toggleFCM(boolean value) {
204 | Pushy.toggleFCM(value, getReactApplicationContext());
205 | }
206 |
207 | @ReactMethod
208 | public void setProxyEndpoint(String proxyEndpoint) {
209 | Pushy.setProxyEndpoint(proxyEndpoint, getReactApplicationContext());
210 | }
211 |
212 | @ReactMethod
213 | public void setEnterpriseCertificate(String enterpriseCert) {
214 | Pushy.setEnterpriseCertificate(enterpriseCert, getReactApplicationContext());
215 | }
216 |
217 | @ReactMethod
218 | public void isRegistered(Promise promise) {
219 | promise.resolve(Pushy.isRegistered(getReactApplicationContext()));
220 | }
221 |
222 | @ReactMethod
223 | public void getDeviceCredentials(Promise promise) {
224 | promise.resolve(Pushy.getDeviceCredentials(getReactApplicationContext()));
225 | }
226 |
227 | private PendingIntent getMainActivityPendingIntent(Context context, ReadableMap payload) {
228 | // Get launcher activity intent
229 | Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getApplicationContext().getPackageName());
230 |
231 | // Make sure to update the activity if it exists
232 | launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
233 |
234 | // Attempt to convert ReadableMap to JSON string
235 | String json = "{}";
236 |
237 | try {
238 | // Fail gracefully
239 | json = PushyMapUtils.convertMapToJson(payload).toString();
240 | }
241 | catch(Exception e) {
242 | // Log exception
243 | PushyLogger.e("Failed to convert ReadableMap into JSON string", e);
244 | }
245 |
246 | // Pass payload data into PendingIntent
247 | launchIntent.putExtra(PushyIntentExtras.NOTIFICATION_CLICKED, true);
248 | launchIntent.putExtra(PushyIntentExtras.NOTIFICATION_PAYLOAD, json);
249 |
250 | // Convert intent into pending intent
251 | return PendingIntent.getActivity(context, json.hashCode(), launchIntent, PendingIntent.FLAG_IMMUTABLE);
252 | }
253 |
254 | @ReactMethod
255 | public void setNotificationIcon(final String iconResourceName) {
256 | // Store in SharedPreferences using PushyPersistence helper
257 | PushyPersistence.setNotificationIcon(iconResourceName, getReactApplicationContext());
258 | }
259 |
260 | private int getNotificationIcon(Context context) {
261 | // Attempt to fetch icon name from SharedPreferences
262 | String icon = PushyPersistence.getNotificationIcon(context);
263 |
264 | // Did we configure a custom icon?
265 | if (icon != null) {
266 | // Cache app resources
267 | Resources resources = context.getResources();
268 |
269 | // Cache app package name
270 | String packageName = context.getPackageName();
271 |
272 | // Look for icon in drawable folders
273 | int iconId = resources.getIdentifier(icon, "drawable", packageName);
274 |
275 | // Found it?
276 | if (iconId != 0) {
277 | return iconId;
278 | }
279 |
280 | // Look for icon in mipmap folders
281 | iconId = resources.getIdentifier(icon, "mipmap", packageName);
282 |
283 | // Found it?
284 | if (iconId != 0) {
285 | return iconId;
286 | }
287 | }
288 |
289 | // Fallback to generic icon
290 | return android.R.drawable.ic_dialog_info;
291 | }
292 |
293 | void onNotificationClicked(Intent intent) {
294 | // No notification clicked?
295 | if (!intent.getBooleanExtra(PushyIntentExtras.NOTIFICATION_CLICKED, false)) {
296 | return;
297 | }
298 |
299 | // Extract payload and invoke notification click listener
300 | String payload = intent.getStringExtra(PushyIntentExtras.NOTIFICATION_PAYLOAD);
301 |
302 | // No payload?
303 | if (PushyStringUtils.stringIsNullOrEmpty(payload)) {
304 | return;
305 | }
306 |
307 | try {
308 | // Parse JSON
309 | JSONObject jsonObject = new JSONObject(payload);
310 |
311 | // Convert into React map format
312 | WritableMap map = PushyMapUtils.convertJsonToMap(jsonObject);
313 |
314 | // Pass to app via React EventEmitter
315 | getReactApplicationContext()
316 | .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
317 | .emit("NotificationClick", map);
318 | }
319 | catch (Exception e) {
320 | // Log exception
321 | PushyLogger.e("Failed to parse JSON into WritableMap", e);
322 | }
323 | }
324 |
325 | @Override
326 | public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
327 | // Do nothing
328 | return;
329 | }
330 |
331 | @Override
332 | public void onNewIntent(Intent intent) {
333 | // Handle notification click
334 | onNotificationClicked(intent);
335 | }
336 | }
--------------------------------------------------------------------------------
/android/src/main/java/me/pushy/sdk/react/receivers/PushReceiver.java:
--------------------------------------------------------------------------------
1 | package me.pushy.sdk.react.receivers;
2 |
3 | import android.content.Intent;
4 | import android.content.Context;
5 | import android.content.BroadcastReceiver;
6 | import android.os.Handler;
7 | import android.os.Looper;
8 |
9 | import me.pushy.sdk.react.services.PushyNotificationService;
10 |
11 | public class PushReceiver extends BroadcastReceiver {
12 | static PushyNotificationService mNotificationService;
13 |
14 | @Override
15 | public void onReceive(final Context context, final Intent intent) {
16 | // Run on main UI thread
17 | new Handler(Looper.getMainLooper()).post(new Runnable() {
18 | @Override
19 | public void run() {
20 | // Instantiate static notification service class
21 | if (mNotificationService == null) {
22 | mNotificationService = new PushyNotificationService(context);
23 | }
24 |
25 | // Execute onStartCommand without actually starting the service (Android O Background Execution Limits)
26 | mNotificationService.onStartCommand(intent, 0, 0);
27 | }
28 | });
29 | }
30 | }
--------------------------------------------------------------------------------
/android/src/main/java/me/pushy/sdk/react/services/PushyNotificationService.java:
--------------------------------------------------------------------------------
1 | package me.pushy.sdk.react.services;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.app.Application;
5 | import android.app.Service;
6 | import android.content.Context;
7 | import android.content.Intent;
8 | import android.os.Bundle;
9 |
10 | import com.facebook.react.HeadlessJsTaskService;
11 | import com.facebook.react.bridge.Arguments;
12 |
13 | import com.facebook.react.jstasks.HeadlessJsTaskConfig;
14 |
15 | import java.lang.reflect.Field;
16 |
17 | import me.pushy.sdk.react.config.PushyHeadlessJSConfig;
18 | import me.pushy.sdk.util.PushyLogger;
19 |
20 | public class PushyNotificationService extends HeadlessJsTaskService {
21 | @SuppressLint("DiscouragedPrivateApi")
22 | public PushyNotificationService(Context context) {
23 | super();
24 |
25 | // Inject synthetic context
26 | attachBaseContext(context);
27 |
28 | // Get Application context object
29 | Application app = (Application) context.getApplicationContext();
30 |
31 | // Use reflection to override the private mApplication field in Service superclass
32 | // To resolve NullPointerException errors when launching the service directly using onStartCommand()
33 | Field field;
34 |
35 | try {
36 | // Get privately declared field
37 | field = Service.class.getDeclaredField("mApplication");
38 | } catch (NoSuchFieldException e) {
39 | // Log exception
40 | PushyLogger.e("Failed to fetch declared field mApplication of Service superclass", e);
41 | return;
42 | }
43 |
44 | // Make it accessible
45 | field.setAccessible(true);
46 |
47 | try {
48 | // Set a new Application value
49 | field.set(this, app);
50 | } catch (IllegalAccessException e) {
51 | // Log exception
52 | PushyLogger.e("Failed to override mApplication field of Service superclass", e);
53 | }
54 | }
55 |
56 | @Override
57 | public HeadlessJsTaskConfig getTaskConfig(Intent intent) {
58 | // Get extras bundle to provide to task
59 | Bundle extras = intent.getExtras();
60 |
61 | // No push payload?
62 | if (extras == null) {
63 | return null;
64 | }
65 |
66 | // Return task config
67 | return new HeadlessJsTaskConfig(PushyHeadlessJSConfig.PUSH_RECEIVER_HEADLESS_TASK_NAME, Arguments.fromBundle(extras), 5000, PushyHeadlessJSConfig.PUSH_RECEIVER_HEADLESS_TASK_FOREGROUND);
68 | }
69 | }
--------------------------------------------------------------------------------
/android/src/main/java/me/pushy/sdk/react/util/PushyMapUtils.java:
--------------------------------------------------------------------------------
1 | package me.pushy.sdk.react.util;
2 |
3 | import com.facebook.react.bridge.ReadableArray;
4 | import com.facebook.react.bridge.ReadableMap;
5 | import com.facebook.react.bridge.ReadableMapKeySetIterator;
6 | import com.facebook.react.bridge.WritableArray;
7 | import com.facebook.react.bridge.WritableMap;
8 | import com.facebook.react.bridge.WritableNativeArray;
9 | import com.facebook.react.bridge.WritableNativeMap;
10 |
11 | import org.json.JSONArray;
12 | import org.json.JSONException;
13 | import org.json.JSONObject;
14 |
15 | import java.util.Iterator;
16 |
17 | public class PushyMapUtils {
18 | public static WritableMap convertJsonToMap(JSONObject jsonObject) throws JSONException {
19 | WritableMap map = new WritableNativeMap();
20 |
21 | Iterator iterator = jsonObject.keys();
22 | while (iterator.hasNext()) {
23 | String key = iterator.next();
24 | Object value = jsonObject.get(key);
25 | if (value instanceof JSONObject) {
26 | map.putMap(key, convertJsonToMap((JSONObject) value));
27 | } else if (value instanceof JSONArray) {
28 | map.putArray(key, convertJsonToArray((JSONArray) value));
29 | } else if (value instanceof Boolean) {
30 | map.putBoolean(key, (Boolean) value);
31 | } else if (value instanceof Integer) {
32 | map.putInt(key, (Integer) value);
33 | } else if (value instanceof Double) {
34 | map.putDouble(key, (Double) value);
35 | } else if (value instanceof String) {
36 | map.putString(key, (String) value);
37 | } else {
38 | map.putString(key, value.toString());
39 | }
40 | }
41 | return map;
42 | }
43 |
44 | public static WritableArray convertJsonToArray(JSONArray jsonArray) throws JSONException {
45 | WritableArray array = new WritableNativeArray();
46 |
47 | for (int i = 0; i < jsonArray.length(); i++) {
48 | Object value = jsonArray.get(i);
49 | if (value instanceof JSONObject) {
50 | array.pushMap(convertJsonToMap((JSONObject) value));
51 | } else if (value instanceof JSONArray) {
52 | array.pushArray(convertJsonToArray((JSONArray) value));
53 | } else if (value instanceof Boolean) {
54 | array.pushBoolean((Boolean) value);
55 | } else if (value instanceof Integer) {
56 | array.pushInt((Integer) value);
57 | } else if (value instanceof Double) {
58 | array.pushDouble((Double) value);
59 | } else if (value instanceof String) {
60 | array.pushString((String) value);
61 | } else {
62 | array.pushString(value.toString());
63 | }
64 | }
65 | return array;
66 | }
67 |
68 | public static JSONObject convertMapToJson(ReadableMap readableMap) throws JSONException {
69 | JSONObject object = new JSONObject();
70 | ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
71 | while (iterator.hasNextKey()) {
72 | String key = iterator.nextKey();
73 | switch (readableMap.getType(key)) {
74 | case Null:
75 | object.put(key, JSONObject.NULL);
76 | break;
77 | case Boolean:
78 | object.put(key, readableMap.getBoolean(key));
79 | break;
80 | case Number:
81 | object.put(key, readableMap.getDouble(key));
82 | break;
83 | case String:
84 | object.put(key, readableMap.getString(key));
85 | break;
86 | case Map:
87 | object.put(key, convertMapToJson(readableMap.getMap(key)));
88 | break;
89 | case Array:
90 | object.put(key, convertArrayToJson(readableMap.getArray(key)));
91 | break;
92 | }
93 | }
94 | return object;
95 | }
96 |
97 | public static JSONArray convertArrayToJson(ReadableArray readableArray) throws JSONException {
98 | JSONArray array = new JSONArray();
99 | for (int i = 0; i < readableArray.size(); i++) {
100 | switch (readableArray.getType(i)) {
101 | case Null:
102 | break;
103 | case Boolean:
104 | array.put(readableArray.getBoolean(i));
105 | break;
106 | case Number:
107 | array.put(readableArray.getDouble(i));
108 | break;
109 | case String:
110 | array.put(readableArray.getString(i));
111 | break;
112 | case Map:
113 | array.put(convertMapToJson(readableArray.getMap(i)));
114 | break;
115 | case Array:
116 | array.put(convertArrayToJson(readableArray.getArray(i)));
117 | break;
118 | }
119 | }
120 | return array;
121 | }
122 |
123 | }
124 |
--------------------------------------------------------------------------------
/android/src/main/java/me/pushy/sdk/react/util/PushyPersistence.java:
--------------------------------------------------------------------------------
1 | package me.pushy.sdk.react.util;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 | import android.preference.PreferenceManager;
6 |
7 | public class PushyPersistence {
8 | public static final String NOTIFICATION_ICON = "pushyNotificationIcon";
9 |
10 | private static SharedPreferences getSettings(Context context) {
11 | // Get default app SharedPreferences
12 | return PreferenceManager.getDefaultSharedPreferences(context);
13 | }
14 |
15 | public static void setNotificationIcon(String icon, Context context) {
16 | // Store notification icon in SharedPreferences
17 | getSettings(context).edit().putString(PushyPersistence.NOTIFICATION_ICON, icon).commit();
18 | }
19 |
20 | public static String getNotificationIcon( Context context) {
21 | // Get notification icon from SharedPreferences
22 | return getSettings(context).getString(PushyPersistence.NOTIFICATION_ICON, null);
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/ios/PushyModule.h:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 | #import
4 |
5 | @interface PushyObj : NSObject
6 | @end
7 |
8 | @interface PushyModule : RCTEventEmitter
9 | + (PushyObj *_Nonnull)getSharedPushyInstance;
10 | + (void)didFinishLaunchingWithOptions:(NSDictionary *_Nonnull)launchOptions;
11 | @end
12 |
13 |
--------------------------------------------------------------------------------
/ios/PushyModule.m:
--------------------------------------------------------------------------------
1 | #import "PushyModule.h"
2 | #import
3 |
4 | @import Pushy;
5 | @implementation PushyModule
6 |
7 | + (void)initialize {
8 | // Module initialized?
9 | if (self == [PushyModule class]) {
10 | // Add observer on UIApplicationDidFinishLaunchingNotification to catch cold start notification click
11 | [[NSNotificationCenter defaultCenter] addObserver:self
12 | selector:@selector(applicationDidFinishLaunching:)
13 | name:UIApplicationDidFinishLaunchingNotification
14 | object:nil];
15 | }
16 | }
17 |
18 | RCT_EXPORT_MODULE();
19 |
20 | Pushy *pushy;
21 | NSDictionary *coldStartNotification;
22 |
23 | - (Pushy *) getPushyInstance
24 | {
25 | // Pushy instance singleton
26 | if (!pushy) {
27 | pushy = [[Pushy alloc]init:[UIApplication sharedApplication]];
28 | }
29 |
30 | return pushy;
31 | }
32 |
33 | + (Pushy *) getSharedPushyInstance
34 | {
35 | // Pushy instance singleton
36 | if (!pushy) {
37 | pushy = [[Pushy alloc]init:[UIApplication sharedApplication]];
38 | }
39 |
40 | return pushy;
41 | }
42 |
43 | + (void)didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
44 | // Old method (leave for backward compatibiliy)
45 | if (launchOptions != nil) {
46 | // Get remote notification (may be nil)
47 | NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
48 |
49 | // Save cold-start notification for later when Pushy.listen() is called
50 | if (remoteNotification != nil) {
51 | coldStartNotification = remoteNotification;
52 | }
53 | }
54 | }
55 |
56 | // Observer on UIApplicationDidFinishLaunchingNotification to catch cold start notification click
57 | + (void)applicationDidFinishLaunching:(NSNotification *)notification {
58 | // Save cold-start notification for later when Pushy.listen() is called
59 | if (notification != nil && notification.userInfo != nil) {
60 | // Extract notification payload from userInfo dictionary
61 | coldStartNotification = [notification.userInfo objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
62 | }
63 | }
64 |
65 | // Check if PushyMQTT class is available (depends on CocoaMQTT)
66 | #if __has_include("MGCDAsyncSocket.h")
67 |
68 | RCT_EXPORT_METHOD(setLocalPushConnectivityConfig:(nonnull NSString *)endpoint port:(nonnull NSNumber *)port keepAlive:(nonnull NSNumber *)keepAlive ssids:(nonnull NSArray *)ssids) {
69 | // iOS 14 and newer
70 | if (@available(iOS 14.0, *)) {
71 | // Configure Local Push Connectivity
72 | [PushyMQTT setLocalPushConnectivityConfigWithEndpoint: endpoint port: port keepAlive: keepAlive ssids: ssids];
73 | }
74 | }
75 |
76 | #endif
77 |
78 | RCT_EXPORT_METHOD(listen)
79 | {
80 | // Run on main thread
81 | dispatch_sync(dispatch_get_main_queue(), ^{
82 | // Handle push notifications
83 | [[self getPushyInstance] setNotificationHandler:^(NSDictionary *data, void (^completionHandler)(UIBackgroundFetchResult)) {
84 | // Print notification payload data
85 | NSLog(@"Received notification: %@", data);
86 |
87 | // Emit RCT event with notification payload dictionary
88 | [self sendEventWithName:@"Notification" body:data];
89 |
90 | // Check if app was inactive (this means notification was clicked)
91 | if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateInactive) {
92 | // Emit RCT notification click event with notification payload dictionary
93 | [self sendEventWithName:@"NotificationClick" body:data];
94 | }
95 |
96 | // Call the completion handler immediately on behalf of the app
97 | completionHandler(UIBackgroundFetchResultNewData);
98 | }];
99 |
100 | // Handle iOS in-app banner notification tap event (iOS 10+)
101 | [[self getPushyInstance] setNotificationClickListener:^(NSDictionary *data) {
102 | // Print event info & notification payload data
103 | NSLog(@"Notification click: %@", data);
104 |
105 | // Emit RTC notification click event with payload dictionary
106 | [self sendEventWithName:@"NotificationClick" body:data];
107 | }];
108 |
109 | // Check for cold start notification (from didFinishLaunchingWithOptions)
110 | if (coldStartNotification != nil) {
111 | // Emit RCT event with notification payload dictionary
112 | [self sendEventWithName:@"Notification" body:coldStartNotification];
113 |
114 | // Cold start notifications were always clicked by the user
115 | [self sendEventWithName:@"NotificationClick" body:coldStartNotification];
116 |
117 | // Clear cold start notification obj to avoid re-delivery on app reload
118 | coldStartNotification = nil;
119 | }
120 | });
121 | }
122 |
123 | RCT_EXPORT_METHOD(setCriticalAlertOption)
124 | {
125 | // Define critical alert notification options
126 | UNAuthorizationOptions options = UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCriticalAlert;
127 |
128 | // Set custom options
129 | [[self getPushyInstance] setCustomNotificationOptions: options];
130 | }
131 |
132 | RCT_EXPORT_METHOD(register:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
133 | {
134 | // Keep track of promise resolve/reject invocation
135 | __block BOOL resolved = NO;
136 |
137 | // Run on main thread
138 | dispatch_sync(dispatch_get_main_queue(), ^{
139 | // Register the device for push notifications
140 | [[self getPushyInstance] register:^(NSError *error, NSString* deviceToken) {
141 | // Handle registration errors
142 | if (error != nil) {
143 | // Avoid resolving if did so in the past
144 | if (!resolved){
145 | resolved = YES;
146 |
147 | // Reject promise with error
148 | reject(@"Error", [NSString stringWithFormat:@"Registration failed: %@", error], error);
149 | }
150 |
151 | return;
152 | }
153 |
154 | // Print device token to console
155 | NSLog(@"Pushy device token: %@", deviceToken);
156 |
157 | // Avoid resolving if did so in the past
158 | if (!resolved){
159 | resolved = YES;
160 |
161 | // Resolve promise with device token
162 | resolve(deviceToken);
163 | }
164 | }];
165 | });
166 | }
167 |
168 | RCT_EXPORT_METHOD(toggleIgnorePushPermissionDenial:(BOOL)toggle)
169 | {
170 | // Enable/disable ignoring push permission denial
171 | [[self getPushyInstance] toggleIgnorePushPermissionDenial:toggle];
172 | }
173 |
174 | RCT_EXPORT_METHOD(unregister)
175 | {
176 | // Unregister the device from receiving notifications
177 | [[self getPushyInstance] unregister];
178 | }
179 |
180 | RCT_EXPORT_METHOD(toggleAPNs:(BOOL)value)
181 | {
182 | // Toggle APNs for Local Push Connectivity support
183 | [[self getPushyInstance] toggleAPNs:value];
184 | }
185 |
186 | RCT_EXPORT_METHOD(toggleInAppBanner:(BOOL)toggle)
187 | {
188 | // Run on main thread
189 | dispatch_sync(dispatch_get_main_queue(), ^{
190 | // Enable/disable in-app notification banners (iOS 10+)
191 | [[self getPushyInstance] toggleInAppBanner:toggle];
192 |
193 | // Toggled off? (after previously being toggled on)
194 | if (!toggle) {
195 | // Reset UNUserNotificationCenterDelegate to nil to avoid displaying banner
196 | [UNUserNotificationCenter currentNotificationCenter].delegate = nil;
197 | }
198 | });
199 | }
200 |
201 |
202 | RCT_EXPORT_METHOD(toggleMethodSwizzling:(BOOL)toggle)
203 | {
204 | // Enable/disable AppDelegate method swizzling
205 | [[self getPushyInstance] toggleMethodSwizzling:toggle];
206 | }
207 |
208 | RCT_EXPORT_METHOD(subscribe:(NSString *)topic resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
209 | {
210 | // Subscribe the device to topic
211 | [[self getPushyInstance] subscribeWithTopic:topic handler:^(NSError *error) {
212 | // Handle errors
213 | if (error != nil) {
214 | // Reject promise
215 | reject(@"Error", [NSString stringWithFormat:@"Subscribe failed: %@", error], error);
216 | return;
217 | }
218 |
219 | // Resolve promise
220 | resolve(@YES);
221 | }];
222 | }
223 |
224 | RCT_EXPORT_METHOD(unsubscribe:(NSString *)topic resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
225 | {
226 | // Unsubscribe the device from topic
227 | [[self getPushyInstance] unsubscribeWithTopic:topic handler:^(NSError *error) {
228 | // Handle errors
229 | if (error != nil) {
230 | // Reject promise
231 | reject(@"Error", [NSString stringWithFormat:@"Unsubscribe failed: %@", error], error);
232 | return;
233 | }
234 |
235 | // Resolve promise
236 | resolve(@YES);
237 | }];
238 | }
239 |
240 | RCT_EXPORT_METHOD(isRegistered:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
241 | {
242 | // Check if registered for push notifications
243 | BOOL isRegistered = [[self getPushyInstance] isRegistered];
244 |
245 | // Send result back to app
246 | resolve([NSNumber numberWithBool:isRegistered]);
247 | }
248 |
249 | RCT_EXPORT_METHOD(setProxyEndpoint:(NSString *)proxyEndpoint)
250 | {
251 | // Empty endpoint?
252 | if ([proxyEndpoint length] == 0) {
253 | proxyEndpoint = nil;
254 | }
255 |
256 | // Set proxy endpoint
257 | [[self getPushyInstance] setProxyEndpointWithProxyEndpoint:proxyEndpoint];
258 | }
259 |
260 | RCT_EXPORT_METHOD(setEnterpriseConfig:(NSString *)apiEndpoint mqttEndpoint:(NSString *)mqttEndpoint)
261 | {
262 | // Empty endpoint?
263 | if ([apiEndpoint length] == 0) {
264 | apiEndpoint = nil;
265 | }
266 |
267 | // Set Pushy Enterprise API endpoint
268 | [[self getPushyInstance] setEnterpriseConfigWithApiEndpoint:apiEndpoint];
269 | }
270 |
271 | RCT_EXPORT_METHOD(setAppId:(NSString *)appId)
272 | {
273 | // Empty App ID?
274 | if ([appId length] == 0) {
275 | appId = nil;
276 | }
277 |
278 | // Set Pushy App ID
279 | [[self getPushyInstance] setAppId:appId];
280 | }
281 |
282 | RCT_EXPORT_METHOD(notify:(NSString *)title message:(NSString *)message payload:(id *)payload)
283 | {
284 | // Run on main thread
285 | dispatch_sync(dispatch_get_main_queue(), ^{
286 | // Display the notification as an alert
287 | UIAlertController * alert = [UIAlertController
288 | alertControllerWithTitle:title
289 | message:message
290 | preferredStyle:UIAlertControllerStyleAlert];
291 |
292 | // Add an action button
293 | [alert addAction:[UIAlertAction
294 | actionWithTitle:@"OK"
295 | style:UIAlertActionStyleDefault
296 | handler:nil]];
297 |
298 | // Show the alert dialog
299 | [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:alert animated:YES completion:nil];
300 | });
301 | }
302 |
303 | RCT_EXPORT_METHOD(setBadge:(nonnull NSNumber *)badge)
304 | {
305 | // Run on main thread
306 | dispatch_sync(dispatch_get_main_queue(), ^{
307 | // Set app badge number
308 | [[UIApplication sharedApplication] setApplicationIconBadgeNumber:[badge intValue]];
309 | });
310 | }
311 |
312 | - (NSArray *)supportedEvents
313 | {
314 | // Emit Notification RTC Events
315 | return @[@"Notification", @"NotificationClick"];
316 | }
317 |
318 | @end
319 |
320 |
--------------------------------------------------------------------------------
/ios/PushyRN.xcodeproj/project.pbxproj:
--------------------------------------------------------------------------------
1 | // !$*UTF8*$!
2 | {
3 | archiveVersion = 1;
4 | classes = {
5 | };
6 | objectVersion = 46;
7 | objects = {
8 |
9 | /* Begin PBXBuildFile section */
10 | E41FA527212448AA006156FA /* PushyResponseException.swift in Sources */ = {isa = PBXBuildFile; fileRef = E41FA51C212448A9006156FA /* PushyResponseException.swift */; };
11 | E41FA528212448AA006156FA /* PushyHTTP.swift in Sources */ = {isa = PBXBuildFile; fileRef = E41FA51D212448A9006156FA /* PushyHTTP.swift */; };
12 | E41FA529212448AA006156FA /* PushySettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = E41FA51E212448A9006156FA /* PushySettings.swift */; };
13 | E41FA52A212448AA006156FA /* Pushy.swift in Sources */ = {isa = PBXBuildFile; fileRef = E41FA51F212448A9006156FA /* Pushy.swift */; };
14 | E41FA52B212448AA006156FA /* PushySwizzler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E41FA520212448A9006156FA /* PushySwizzler.swift */; };
15 | E41FA52C212448AA006156FA /* PushyEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = E41FA521212448A9006156FA /* PushyEnvironment.swift */; };
16 | E41FA52D212448AA006156FA /* PushyRegistrationException.swift in Sources */ = {isa = PBXBuildFile; fileRef = E41FA522212448A9006156FA /* PushyRegistrationException.swift */; };
17 | E41FA52E212448AA006156FA /* PushyKeychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = E41FA523212448AA006156FA /* PushyKeychain.swift */; };
18 | E41FA52F212448AA006156FA /* PushyPubSubException.swift in Sources */ = {isa = PBXBuildFile; fileRef = E41FA524212448AA006156FA /* PushyPubSubException.swift */; };
19 | E41FA530212448AA006156FA /* PushyConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = E41FA525212448AA006156FA /* PushyConfig.swift */; };
20 | E41FA531212448AA006156FA /* PushyNetworkException.swift in Sources */ = {isa = PBXBuildFile; fileRef = E41FA526212448AA006156FA /* PushyNetworkException.swift */; };
21 | E49A4A96212417CE00FBE78B /* PushyModule.m in Sources */ = {isa = PBXBuildFile; fileRef = E49A4A95212417CE00FBE78B /* PushyModule.m */; };
22 | /* End PBXBuildFile section */
23 |
24 | /* Begin PBXCopyFilesBuildPhase section */
25 | 58B511D91A9E6C8500147676 /* CopyFiles */ = {
26 | isa = PBXCopyFilesBuildPhase;
27 | buildActionMask = 2147483647;
28 | dstPath = "include/$(PRODUCT_NAME)";
29 | dstSubfolderSpec = 16;
30 | files = (
31 | );
32 | runOnlyForDeploymentPostprocessing = 0;
33 | };
34 | /* End PBXCopyFilesBuildPhase section */
35 |
36 | /* Begin PBXFileReference section */
37 | 134814201AA4EA6300B7C361 /* libPushyRN.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPushyRN.a; sourceTree = BUILT_PRODUCTS_DIR; };
38 | E41FA51C212448A9006156FA /* PushyResponseException.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushyResponseException.swift; sourceTree = ""; };
39 | E41FA51D212448A9006156FA /* PushyHTTP.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushyHTTP.swift; sourceTree = ""; };
40 | E41FA51E212448A9006156FA /* PushySettings.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushySettings.swift; sourceTree = ""; };
41 | E41FA51F212448A9006156FA /* Pushy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pushy.swift; sourceTree = ""; };
42 | E41FA520212448A9006156FA /* PushySwizzler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushySwizzler.swift; sourceTree = ""; };
43 | E41FA521212448A9006156FA /* PushyEnvironment.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushyEnvironment.swift; sourceTree = ""; };
44 | E41FA522212448A9006156FA /* PushyRegistrationException.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushyRegistrationException.swift; sourceTree = ""; };
45 | E41FA523212448AA006156FA /* PushyKeychain.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushyKeychain.swift; sourceTree = ""; };
46 | E41FA524212448AA006156FA /* PushyPubSubException.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushyPubSubException.swift; sourceTree = ""; };
47 | E41FA525212448AA006156FA /* PushyConfig.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushyConfig.swift; sourceTree = ""; };
48 | E41FA526212448AA006156FA /* PushyNetworkException.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushyNetworkException.swift; sourceTree = ""; };
49 | E49A4A95212417CE00FBE78B /* PushyModule.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = PushyModule.m; sourceTree = ""; };
50 | E49A4A97212417E300FBE78B /* PushyModule.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PushyModule.h; sourceTree = ""; };
51 | /* End PBXFileReference section */
52 |
53 | /* Begin PBXFrameworksBuildPhase section */
54 | 58B511D81A9E6C8500147676 /* Frameworks */ = {
55 | isa = PBXFrameworksBuildPhase;
56 | buildActionMask = 2147483647;
57 | files = (
58 | );
59 | runOnlyForDeploymentPostprocessing = 0;
60 | };
61 | /* End PBXFrameworksBuildPhase section */
62 |
63 | /* Begin PBXGroup section */
64 | 134814211AA4EA7D00B7C361 /* Products */ = {
65 | isa = PBXGroup;
66 | children = (
67 | 134814201AA4EA6300B7C361 /* libPushyRN.a */,
68 | );
69 | name = Products;
70 | sourceTree = "";
71 | };
72 | 58B511D21A9E6C8500147676 = {
73 | isa = PBXGroup;
74 | children = (
75 | E41FA5E121244FC7006156FA /* SDK */,
76 | E49A4A97212417E300FBE78B /* PushyModule.h */,
77 | E49A4A95212417CE00FBE78B /* PushyModule.m */,
78 | 134814211AA4EA7D00B7C361 /* Products */,
79 | 665F0B9C1EA82E940088A613 /* Frameworks */,
80 | );
81 | sourceTree = "";
82 | };
83 | 665F0B9C1EA82E940088A613 /* Frameworks */ = {
84 | isa = PBXGroup;
85 | children = (
86 | );
87 | name = Frameworks;
88 | sourceTree = "";
89 | };
90 | E41FA5E121244FC7006156FA /* SDK */ = {
91 | isa = PBXGroup;
92 | children = (
93 | E41FA51F212448A9006156FA /* Pushy.swift */,
94 | E41FA525212448AA006156FA /* PushyConfig.swift */,
95 | E41FA521212448A9006156FA /* PushyEnvironment.swift */,
96 | E41FA51D212448A9006156FA /* PushyHTTP.swift */,
97 | E41FA523212448AA006156FA /* PushyKeychain.swift */,
98 | E41FA526212448AA006156FA /* PushyNetworkException.swift */,
99 | E41FA524212448AA006156FA /* PushyPubSubException.swift */,
100 | E41FA522212448A9006156FA /* PushyRegistrationException.swift */,
101 | E41FA51C212448A9006156FA /* PushyResponseException.swift */,
102 | E41FA51E212448A9006156FA /* PushySettings.swift */,
103 | E41FA520212448A9006156FA /* PushySwizzler.swift */,
104 | );
105 | path = SDK;
106 | sourceTree = "";
107 | };
108 | /* End PBXGroup section */
109 |
110 | /* Begin PBXNativeTarget section */
111 | 58B511DA1A9E6C8500147676 /* PushyRN */ = {
112 | isa = PBXNativeTarget;
113 | buildConfigurationList = 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "PushyRN" */;
114 | buildPhases = (
115 | 58B511D71A9E6C8500147676 /* Sources */,
116 | 58B511D81A9E6C8500147676 /* Frameworks */,
117 | 58B511D91A9E6C8500147676 /* CopyFiles */,
118 | );
119 | buildRules = (
120 | );
121 | dependencies = (
122 | );
123 | name = PushyRN;
124 | productName = RCTDataManager;
125 | productReference = 134814201AA4EA6300B7C361 /* libPushyRN.a */;
126 | productType = "com.apple.product-type.library.static";
127 | };
128 | /* End PBXNativeTarget section */
129 |
130 | /* Begin PBXProject section */
131 | 58B511D31A9E6C8500147676 /* Project object */ = {
132 | isa = PBXProject;
133 | attributes = {
134 | LastUpgradeCheck = 0920;
135 | ORGANIZATIONNAME = Facebook;
136 | TargetAttributes = {
137 | 58B511DA1A9E6C8500147676 = {
138 | CreatedOnToolsVersion = 6.1.1;
139 | LastSwiftMigration = 0920;
140 | };
141 | };
142 | };
143 | buildConfigurationList = 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "PushyRN" */;
144 | compatibilityVersion = "Xcode 3.2";
145 | developmentRegion = English;
146 | hasScannedForEncodings = 0;
147 | knownRegions = (
148 | en,
149 | );
150 | mainGroup = 58B511D21A9E6C8500147676;
151 | productRefGroup = 58B511D21A9E6C8500147676;
152 | projectDirPath = "";
153 | projectRoot = "";
154 | targets = (
155 | 58B511DA1A9E6C8500147676 /* PushyRN */,
156 | );
157 | };
158 | /* End PBXProject section */
159 |
160 | /* Begin PBXSourcesBuildPhase section */
161 | 58B511D71A9E6C8500147676 /* Sources */ = {
162 | isa = PBXSourcesBuildPhase;
163 | buildActionMask = 2147483647;
164 | files = (
165 | E41FA529212448AA006156FA /* PushySettings.swift in Sources */,
166 | E41FA52E212448AA006156FA /* PushyKeychain.swift in Sources */,
167 | E41FA530212448AA006156FA /* PushyConfig.swift in Sources */,
168 | E41FA52A212448AA006156FA /* Pushy.swift in Sources */,
169 | E41FA527212448AA006156FA /* PushyResponseException.swift in Sources */,
170 | E41FA52F212448AA006156FA /* PushyPubSubException.swift in Sources */,
171 | E41FA528212448AA006156FA /* PushyHTTP.swift in Sources */,
172 | E41FA52D212448AA006156FA /* PushyRegistrationException.swift in Sources */,
173 | E41FA531212448AA006156FA /* PushyNetworkException.swift in Sources */,
174 | E49A4A96212417CE00FBE78B /* PushyModule.m in Sources */,
175 | E41FA52C212448AA006156FA /* PushyEnvironment.swift in Sources */,
176 | E41FA52B212448AA006156FA /* PushySwizzler.swift in Sources */,
177 | );
178 | runOnlyForDeploymentPostprocessing = 0;
179 | };
180 | /* End PBXSourcesBuildPhase section */
181 |
182 | /* Begin XCBuildConfiguration section */
183 | 58B511ED1A9E6C8500147676 /* Debug */ = {
184 | isa = XCBuildConfiguration;
185 | buildSettings = {
186 | ALWAYS_SEARCH_USER_PATHS = NO;
187 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
188 | CLANG_CXX_LIBRARY = "libc++";
189 | CLANG_ENABLE_MODULES = YES;
190 | CLANG_ENABLE_OBJC_ARC = YES;
191 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
192 | CLANG_WARN_BOOL_CONVERSION = YES;
193 | CLANG_WARN_COMMA = YES;
194 | CLANG_WARN_CONSTANT_CONVERSION = YES;
195 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
196 | CLANG_WARN_EMPTY_BODY = YES;
197 | CLANG_WARN_ENUM_CONVERSION = YES;
198 | CLANG_WARN_INFINITE_RECURSION = YES;
199 | CLANG_WARN_INT_CONVERSION = YES;
200 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
201 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
202 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
203 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
204 | CLANG_WARN_STRICT_PROTOTYPES = YES;
205 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
206 | CLANG_WARN_UNREACHABLE_CODE = YES;
207 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
208 | COPY_PHASE_STRIP = NO;
209 | DEFINES_MODULE = YES;
210 | ENABLE_STRICT_OBJC_MSGSEND = YES;
211 | ENABLE_TESTABILITY = YES;
212 | GCC_C_LANGUAGE_STANDARD = gnu99;
213 | GCC_DYNAMIC_NO_PIC = NO;
214 | GCC_NO_COMMON_BLOCKS = YES;
215 | GCC_OPTIMIZATION_LEVEL = 0;
216 | GCC_PREPROCESSOR_DEFINITIONS = (
217 | "DEBUG=1",
218 | "$(inherited)",
219 | );
220 | GCC_SYMBOLS_PRIVATE_EXTERN = NO;
221 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
222 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
223 | GCC_WARN_UNDECLARED_SELECTOR = YES;
224 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
225 | GCC_WARN_UNUSED_FUNCTION = YES;
226 | GCC_WARN_UNUSED_VARIABLE = YES;
227 | IPHONEOS_DEPLOYMENT_TARGET = 8.0;
228 | MTL_ENABLE_DEBUG_INFO = YES;
229 | ONLY_ACTIVE_ARCH = YES;
230 | SDKROOT = iphoneos;
231 | };
232 | name = Debug;
233 | };
234 | 58B511EE1A9E6C8500147676 /* Release */ = {
235 | isa = XCBuildConfiguration;
236 | buildSettings = {
237 | ALWAYS_SEARCH_USER_PATHS = NO;
238 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
239 | CLANG_CXX_LIBRARY = "libc++";
240 | CLANG_ENABLE_MODULES = YES;
241 | CLANG_ENABLE_OBJC_ARC = YES;
242 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
243 | CLANG_WARN_BOOL_CONVERSION = YES;
244 | CLANG_WARN_COMMA = YES;
245 | CLANG_WARN_CONSTANT_CONVERSION = YES;
246 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
247 | CLANG_WARN_EMPTY_BODY = YES;
248 | CLANG_WARN_ENUM_CONVERSION = YES;
249 | CLANG_WARN_INFINITE_RECURSION = YES;
250 | CLANG_WARN_INT_CONVERSION = YES;
251 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
252 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
253 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
254 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
255 | CLANG_WARN_STRICT_PROTOTYPES = YES;
256 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
257 | CLANG_WARN_UNREACHABLE_CODE = YES;
258 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
259 | COPY_PHASE_STRIP = YES;
260 | DEFINES_MODULE = YES;
261 | ENABLE_NS_ASSERTIONS = NO;
262 | ENABLE_STRICT_OBJC_MSGSEND = YES;
263 | GCC_C_LANGUAGE_STANDARD = gnu99;
264 | GCC_NO_COMMON_BLOCKS = YES;
265 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
266 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
267 | GCC_WARN_UNDECLARED_SELECTOR = YES;
268 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
269 | GCC_WARN_UNUSED_FUNCTION = YES;
270 | GCC_WARN_UNUSED_VARIABLE = YES;
271 | IPHONEOS_DEPLOYMENT_TARGET = 8.0;
272 | MTL_ENABLE_DEBUG_INFO = NO;
273 | SDKROOT = iphoneos;
274 | VALIDATE_PRODUCT = YES;
275 | };
276 | name = Release;
277 | };
278 | 58B511F01A9E6C8500147676 /* Debug */ = {
279 | isa = XCBuildConfiguration;
280 | buildSettings = {
281 | CLANG_ENABLE_MODULES = YES;
282 | DEFINES_MODULE = YES;
283 | HEADER_SEARCH_PATHS = (
284 | "$(inherited)",
285 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include,
286 | "$(SRCROOT)/../../../React/**",
287 | "$(SRCROOT)/../../react-native/React/**",
288 | );
289 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
290 | LIBRARY_SEARCH_PATHS = "$(inherited)";
291 | OTHER_LDFLAGS = "-ObjC";
292 | PRODUCT_NAME = PushyRN;
293 | SKIP_INSTALL = YES;
294 | SWIFT_OPTIMIZATION_LEVEL = "-Onone";
295 | SWIFT_VERSION = 4.2;
296 | };
297 | name = Debug;
298 | };
299 | 58B511F11A9E6C8500147676 /* Release */ = {
300 | isa = XCBuildConfiguration;
301 | buildSettings = {
302 | CLANG_ENABLE_MODULES = YES;
303 | DEFINES_MODULE = YES;
304 | HEADER_SEARCH_PATHS = (
305 | "$(inherited)",
306 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include,
307 | "$(SRCROOT)/../../../React/**",
308 | "$(SRCROOT)/../../react-native/React/**",
309 | );
310 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
311 | LIBRARY_SEARCH_PATHS = "$(inherited)";
312 | OTHER_LDFLAGS = "-ObjC";
313 | PRODUCT_NAME = PushyRN;
314 | SKIP_INSTALL = YES;
315 | SWIFT_VERSION = 4.2;
316 | };
317 | name = Release;
318 | };
319 | /* End XCBuildConfiguration section */
320 |
321 | /* Begin XCConfigurationList section */
322 | 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "PushyRN" */ = {
323 | isa = XCConfigurationList;
324 | buildConfigurations = (
325 | 58B511ED1A9E6C8500147676 /* Debug */,
326 | 58B511EE1A9E6C8500147676 /* Release */,
327 | );
328 | defaultConfigurationIsVisible = 0;
329 | defaultConfigurationName = Release;
330 | };
331 | 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "PushyRN" */ = {
332 | isa = XCConfigurationList;
333 | buildConfigurations = (
334 | 58B511F01A9E6C8500147676 /* Debug */,
335 | 58B511F11A9E6C8500147676 /* Release */,
336 | );
337 | defaultConfigurationIsVisible = 0;
338 | defaultConfigurationName = Release;
339 | };
340 | /* End XCConfigurationList section */
341 | };
342 | rootObject = 58B511D31A9E6C8500147676 /* Project object */;
343 | }
344 |
--------------------------------------------------------------------------------
/ios/PushyRN.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/lib/Pushy.d.ts:
--------------------------------------------------------------------------------
1 | // Type definitions for pushy-react-native
2 | // Project: https://github.com/pushy/pushy-react-native
3 | // Definitions by: Fabian Kuentzler
4 |
5 | declare module 'pushy-react-native' {
6 | interface Pushy {
7 | /**
8 | * By default, the SDK will automatically authenticate using your iOS app's Bundle ID.
9 | *
10 | * You can manually pass in your Pushy App ID (Pushy Dashboard -> Click your app -> App Settings -> App ID) to override this behavior.
11 | */
12 | setAppId(appId: string): void;
13 |
14 | /**
15 | * Starts Pushy's internal notification listening service, if necessary.
16 | */
17 | listen(): void;
18 |
19 | /**
20 | * Check if the device is registered.
21 | *
22 | * @returns A boolean indicating whether the device is registered or not.
23 | */
24 | isRegistered(): Promise;
25 |
26 | /**
27 | * Register the device for push notifications.
28 | *
29 | * @returns The Pushy device token
30 | */
31 | register(): Promise;
32 |
33 | /**
34 | * Unregister the device from receiving notifications.
35 | */
36 | unregister(): void;
37 |
38 | /**
39 | * Set up the notification listener.
40 | *
41 | * This method can only be called once for your entire app lifecycle, therefore, it should not be invoked within a Component lifecycle event.
42 | *
43 | * @param callback This function will be invoked when a new push notification arrives.
44 | */
45 | setNotificationListener(callback: (data: string | object) => Promise): void;
46 |
47 | /**
48 | * Set up the notification click listener.
49 | *
50 | * @param callback This function will be invoked when the user taps on a push notification.
51 | */
52 | setNotificationClickListener(callback: (data: string | object) => void): void;
53 |
54 | /**
55 | * Calling this method will result in Platform dependent behaviour.
56 | *
57 | * Android: Displays a system notification.
58 | *
59 | * iOS: Displays an alert dialog.
60 | *
61 | * @param title The notification title.
62 | * @param message The notification message.
63 | * @param data The payload object.
64 | */
65 | notify(title: string, message: string, data: object): void;
66 |
67 | /**
68 | * Subscribe the user to a topic.
69 | *
70 | * @param topic The topic to subscribe to.
71 | */
72 | subscribe(topic: string): Promise;
73 |
74 | /**
75 | * Unsubscribe the user from a topic.
76 | *
77 | * @param topic The topic to unsubscribe from.
78 | */
79 | unsubscribe(topic: string): Promise;
80 |
81 | /**
82 | * Android specific.
83 | *
84 | * Toggle FCM fallback
85 | *
86 | * @param enabled A boolean indicating whether the FCM fallback should be enabled.
87 | */
88 | toggleFCM(enabled: boolean): void;
89 |
90 | /**
91 | * iOS specific.
92 | *
93 | * Toggle the In-App Banner.
94 | *
95 | * @param enabled A boolean indicating whether the In-App Banner should be enabled.
96 | */
97 | toggleInAppBanner(enabled: boolean): void;
98 |
99 | /**
100 | * iOS specific.
101 | *
102 | * Toggle ignoring push permission denial
103 | *
104 | * @param enabled A boolean indicating whether an error should not be thrown when the push permission is denied by the user.
105 | */
106 | toggleIgnorePushPermissionDenial(enabled: boolean): void;
107 |
108 | /**
109 | * iOS specific.
110 | *
111 | * By default, the SDK will use method swizzling to hook into the iOS AppDelegate's APNs callbacks.
112 | * You can disable method swizzling by calling this method.
113 | *
114 | * @param enabled A boolean indicating whether method swizzling should be enabled.
115 | */
116 | toggleMethodSwizzling(enabled: boolean): void;
117 |
118 | /**
119 | * iOS specific.
120 | *
121 | * By default, the SDK will register for notifications with the Apple Push Notification Service.
122 | * This can be disabled for on-premises Pushy Enterprise deployments making use of Local Push Connectivity to deliver notifications.
123 | *
124 | * @param enabled A boolean indicating whether APNs integration should be enabled.
125 | */
126 | toggleAPNs(enabled: boolean): void;
127 |
128 | /**
129 | * iOS specific.
130 | *
131 | * On-premises Pushy Enterprise customers can use this method to enable Local Push Connectivity.
132 | *
133 | * @param endpoint The Pushy Enterprise deployment hostname.
134 | * @param port The Pushy Enterprise deployment MQTTS port number.
135 | * @param keepAlive The desired connection keep alive interval in seconds (300 is recommended).
136 | * @param ssids A string array of valid Wi-FI SSIDs that have access to the on-premises Pushy Enterprise deployment.
137 | */
138 | setLocalPushConnectivityConfig(endpint: string, port: number, keepAlive: number, ssids: [String]): void;
139 |
140 | /**
141 | * iOS specific.
142 | *
143 | * Set the iOS Badge count.
144 | *
145 | * @param count The new count for the iOS Badge.
146 | */
147 | setBadge(count: number): void;
148 |
149 | /**
150 | * Android specific.
151 | *
152 | * Optionally configure a custom notification icon for incoming Android notifications
153 | * by placing icon file(s) in `android/app/src/main/res/drawable-*` and calling this method
154 | * after calling `Pushy.listen()`.
155 | *
156 | * @param icon The name of the icon file.
157 | */
158 | setNotificationIcon(icon: string): void;
159 |
160 | /**
161 | * Android specific.
162 | *
163 | * Enables foreground service mode. The SDK will create a foreground service that
164 | * the Android OS will never terminate, which will ensure notification delivery in
165 | * the background and low memory state.
166 | *
167 | * @param toggle A boolean indicating whether foreground service mode should be enabled.
168 | */
169 | toggleForegroundService(enabled: boolean): void;
170 |
171 | /**
172 | * Pushy Enterprise customers can use this method to enable Pushy Enterprise integration.
173 | *
174 | * @param apiEndpoint The Pushy Enterprise API hostname (string).
175 | * @param mqttEndpoint The Pushy Enterprise MQTTS hostname (string).
176 | */
177 | setEnterpriseConfig(apiEndoint: string, mqttEndpoint: string): void;
178 | }
179 |
180 | const pushy: Pushy;
181 | }
182 |
183 | export default pushy;
184 |
--------------------------------------------------------------------------------
/lib/Pushy.js:
--------------------------------------------------------------------------------
1 | import { Platform, AppRegistry, NativeModules, NativeEventEmitter } from 'react-native';
2 |
3 | // Expose all native PushyModule methods
4 | const Pushy = NativeModules.PushyModule;
5 |
6 | // Pushy module not loaded?
7 | if (!Pushy) {
8 | // Are we running on an Android device?
9 | if (Platform.OS === 'android') {
10 | // Log fatal error
11 | console.error('Pushy native module not loaded, please include the PushyPackage() declaration within your app\'s MainApplication.getPackages() implementation.');
12 | }
13 | else if (Platform.OS === 'ios') {
14 | // Log fatal error
15 | console.error('Pushy native module not loaded, please make sure to run "react-native link pushy-react-native" to link the native library to your project.');
16 | }
17 | }
18 | else {
19 | // Android: Define placeholder methods for RN built in Event Emitter calls
20 | if (Platform.OS === 'android') {
21 | Pushy.addListener = () => { };
22 | Pushy.removeListeners = () => { };
23 | }
24 |
25 | // Create event emitter
26 | const pushyEventEmitter = new NativeEventEmitter(Pushy);
27 |
28 | // Expose custom notification listener
29 | Pushy.setNotificationListener = (handler) => {
30 | // iOS event emitter subscription
31 | if (Platform.OS === 'ios') {
32 | // Remove previously set listeners
33 | pushyEventEmitter.removeAllListeners('Notification');
34 |
35 | // Subscribe to new notification events
36 | pushyEventEmitter.addListener('Notification', handler);
37 | }
38 | // Android headless task registration
39 | else if (Platform.OS === 'android' && !Pushy.headlessTaskRegistered) {
40 | // Only call AppRegistry.registerHeadlessTask() once
41 | Pushy.headlessTaskRegistered = true;
42 |
43 | // Listen for push notifications via Headless JS task
44 | AppRegistry.registerHeadlessTask('PushyPushReceiver', () => {
45 | // React Native will execute the handler via Headless JS when the task is called natively
46 | return handler;
47 | });
48 | }
49 | };
50 |
51 | // Expose custom notification click listener
52 | Pushy.setNotificationClickListener = (handler) => {
53 | // Remove previously set listeners
54 | pushyEventEmitter.removeAllListeners('NotificationClick');
55 |
56 | // Subscribe to new notification events
57 | pushyEventEmitter.addListener('NotificationClick', handler);
58 | };
59 |
60 | // Android: Define placeholder method(s) for iOS-only functionality
61 | if (Platform.OS === 'android') {
62 | Pushy.setBadge = () => { };
63 | Pushy.toggleAPNs = () => { };
64 | Pushy.toggleInAppBanner = () => { };
65 | Pushy.setLocalPushConnectivityConfig = () => { };
66 | Pushy.toggleIgnorePushPermissionDenial = () => { };
67 | Pushy.toggleMethodSwizzling = () => { };
68 | }
69 |
70 | // iOS: Define placeholder method(s) for Android-only functionality
71 | if (Platform.OS === 'ios') {
72 | Pushy.toggleFCM = () => { };
73 | Pushy.setNotificationIcon = () => { };
74 | Pushy.setHeartbeatInterval = () => { };
75 | Pushy.setEnterpriseCertificate = () => { };
76 | Pushy.toggleForegroundService = () => { };
77 | Pushy.toggleDirectConnectivity = () => { };
78 | Pushy.togglePermissionVerification = () => { };
79 | }
80 | }
81 |
82 | // Expose module
83 | export default Pushy;
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "pushy-react-native",
3 | "version": "1.0.57",
4 | "description": "The official Pushy SDK for React Native apps.",
5 | "main": "lib/Pushy.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "repository": {
10 | "type": "git",
11 | "url": "git+https://github.com/pushy/pushy-react-native.git"
12 | },
13 | "author": "Pushy ",
14 | "license": "Apache-2.0",
15 | "bugs": {
16 | "url": "https://github.com/pushy/pushy-react-native/issues"
17 | },
18 | "homepage": "https://github.com/pushy/pushy-react-native#readme",
19 | "dependencies": {}
20 | }
21 |
--------------------------------------------------------------------------------