@pushpilotai/react-native 0.0.0-stage → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/PushPilotReactNative.podspec +27 -0
- package/README.md +409 -2
- package/android/build.gradle +38 -0
- package/android/src/main/AndroidManifest.xml +24 -0
- package/android/src/main/java/ai/pushpilot/reactnative/PushPilotMessageReceiver.kt +42 -0
- package/android/src/main/java/ai/pushpilot/reactnative/PushPilotModule.kt +152 -0
- package/android/src/main/java/ai/pushpilot/reactnative/PushPilotPackage.kt +28 -0
- package/android/src/main/java/ai/pushpilot/reactnative/PushPilotStartupProvider.kt +31 -0
- package/android/src/main/java/ai/pushpilot/reactnative/PushPilotTaps.kt +95 -0
- package/ios/RNPushPilot.h +12 -0
- package/ios/RNPushPilot.mm +237 -0
- package/ios/RNPushPilotBridge.swift +90 -0
- package/ios/RNPushPilotNotifications.swift +96 -0
- package/ios/RNPushPilotToken.swift +29 -0
- package/lib/module/NativePushPilot.js +9 -0
- package/lib/module/NativePushPilot.js.map +1 -0
- package/lib/module/index.js +149 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/package.json +1 -0
- package/lib/typescript/package.json +1 -0
- package/lib/typescript/src/NativePushPilot.d.ts +22 -0
- package/lib/typescript/src/NativePushPilot.d.ts.map +1 -0
- package/lib/typescript/src/index.d.ts +82 -0
- package/lib/typescript/src/index.d.ts.map +1 -0
- package/package.json +147 -4
- package/src/NativePushPilot.ts +39 -0
- package/src/index.tsx +208 -0
package/README.md
CHANGED
|
@@ -1,3 +1,410 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @pushpilotai/react-native
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
React Native wrapper for the PushPilot SDK. It registers your app's installation with PushPilot and passes in its push address: the Firebase Cloud Messaging (FCM) identifier on Android and the Apple (APNs) device token on iOS. You can then send pushes to individual users from the PushPilot dashboard. PushPilot pushes are shown and their taps recorded natively, with no JavaScript running.
|
|
4
|
+
|
|
5
|
+
- A thin layer over the native [Android SDK](https://github.com/pushpilotai/pushpilot-android) (`ai.pushpilot:sdk` 2.2.0) and [iOS SDK](https://github.com/pushpilotai/pushpilot-ios) (Swift package `PushPilot` 2.2.0). Every call goes straight to them; they do all syncing, retrying, storage, display and validation.
|
|
6
|
+
- No Firebase dependency. On Android your app keeps its own Firebase setup and passes the identifier in. iOS needs no Firebase at all: PushPilot sends to Apple directly.
|
|
7
|
+
- Never asks for notification permission. It reports whatever the user chose.
|
|
8
|
+
- Every call returns nothing and never throws into your app. Problems are logged.
|
|
9
|
+
|
|
10
|
+
## Requirements
|
|
11
|
+
|
|
12
|
+
- React Native 0.81 or later. Built for the New Architecture; it also works with the New Architecture turned off on React Native 0.81, the last version that allows that.
|
|
13
|
+
- iOS 15.1 or later, Android 7 (API 24) or later (React Native's own minimums).
|
|
14
|
+
- A native build: a bare React Native app or an Expo development build. It cannot work in Expo Go, which has no way to add native code; there every call just logs a warning.
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install @pushpilotai/react-native
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Then `cd ios && pod install`. Autolinking adds the native module on both platforms.
|
|
23
|
+
|
|
24
|
+
## Integrate (bare React Native)
|
|
25
|
+
|
|
26
|
+
### Both platforms
|
|
27
|
+
|
|
28
|
+
1. **Create the app in PushPilot** (dashboard › Apps) and copy its public SDK key. For iOS this needs an APNs push project first; see [iOS](#ios) step 1.
|
|
29
|
+
2. **Initialise once at startup**, at the top level of `index.js` or `App.tsx`:
|
|
30
|
+
|
|
31
|
+
```tsx
|
|
32
|
+
import PushPilot from '@pushpilotai/react-native';
|
|
33
|
+
|
|
34
|
+
PushPilot.init('pp_sdk_...');
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
3. **Identify the user** after login with `PushPilot.setExternalUserId(user.id)` and call `PushPilot.logout()` at logout.
|
|
38
|
+
4. **Ask for notification permission yourself**, when it suits your app (below for each platform). The SDK reads the result each time the app comes to the foreground.
|
|
39
|
+
5. **Optional: handle taps in JavaScript.** By default a tapped PushPilot push opens its link through the system, or just your app when it has none. To route links yourself, or to read the push's custom `data`, set handlers **before `init`**, so the tap that launched a killed app reaches them too:
|
|
40
|
+
|
|
41
|
+
```tsx
|
|
42
|
+
PushPilot.setLinkHandler((url) => {
|
|
43
|
+
// the tapped push's link: navigate to its screen instead of the system opening it
|
|
44
|
+
});
|
|
45
|
+
PushPilot.setTapHandler(({ notificationId, data }) => {
|
|
46
|
+
// every tap that opens the app, e.g. data.order_id
|
|
47
|
+
});
|
|
48
|
+
PushPilot.init('pp_sdk_...');
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Both work the same on Android and iOS. Taps that arrive before JavaScript has started wait for `init` and then go to the handlers set by then; each tap reaches each handler once. Without a link handler at that point, links open in the system; without a tap handler, taps are not reported. For a tap with a link, the tap handler runs first, then the link handler. [Tap details](#taps-on-android-and-ios).
|
|
52
|
+
|
|
53
|
+
Calls made before `init` are queued by the native SDKs and applied once it runs, so the order of these steps does not matter.
|
|
54
|
+
|
|
55
|
+
### Android
|
|
56
|
+
|
|
57
|
+
1. **Set up Firebase Cloud Messaging**, usually with [React Native Firebase](https://rnfirebase.io/messaging/usage): `@react-native-firebase/app` and `@react-native-firebase/messaging`, plus your `google-services.json`. Any library that brings in Firebase Messaging works.
|
|
58
|
+
2. **Forward the push identifier** with `setPushToken`. Firebase is replacing FCM registration tokens with Firebase Installation IDs (FIDs); PushPilot accepts either. Pass only one kind. With React Native Firebase 27 or later, prefer the FID: add `"messaging_installation_id_enabled": true` under `"react-native"` in `firebase.json` (Expo: the messaging plugin's `installationIdEnabled: true`), then:
|
|
59
|
+
|
|
60
|
+
```tsx
|
|
61
|
+
import { Platform } from 'react-native';
|
|
62
|
+
import { getMessaging, onRegistered, register } from '@react-native-firebase/messaging';
|
|
63
|
+
|
|
64
|
+
if (Platform.OS === 'android') {
|
|
65
|
+
const messaging = getMessaging();
|
|
66
|
+
onRegistered(messaging, PushPilot.setPushToken); // the current FID and every new one
|
|
67
|
+
register(messaging);
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Without that opt-in, or on older versions, forward the FCM token instead. The opt-in turns these calls off, so never mix the two:
|
|
72
|
+
|
|
73
|
+
```tsx
|
|
74
|
+
import { getToken, onTokenRefresh } from '@react-native-firebase/messaging';
|
|
75
|
+
|
|
76
|
+
getToken(messaging).then(PushPilot.setPushToken);
|
|
77
|
+
onTokenRefresh(messaging, PushPilot.setPushToken);
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Firebase's "installation ID" (the FID) is a Firebase identifier you pass in as the push identifier. It is not PushPilot's own installation id, which the SDK creates and stores by itself.
|
|
81
|
+
|
|
82
|
+
3. **Nothing else.** PushPilot pushes are shown by the SDK, with image and buttons, whether the app is open, in the background or killed ([how](#android-how-pushes-reach-the-sdk)). Do not show them yourself. In your own `onMessage` or `setBackgroundMessageHandler`, skip them:
|
|
83
|
+
|
|
84
|
+
```tsx
|
|
85
|
+
onMessage(messaging, (message) => {
|
|
86
|
+
if (PushPilot.handleMessage(message.data)) return; // already shown by PushPilot
|
|
87
|
+
// your own pushes
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
If you also have a native `FirebaseMessagingService`, do not call the Android SDK's `PushPilot.handleMessage` from it: the wrapper already does, and the push would be shown twice.
|
|
92
|
+
|
|
93
|
+
4. **Permission:** `PermissionsAndroid.request('android.permission.POST_NOTIFICATIONS')` on Android 13 and later.
|
|
94
|
+
|
|
95
|
+
Tapping a PushPilot push records the click and opens its link, or your launcher activity when it has none. To route links or read the push's `data` in JavaScript, see [Both platforms](#both-platforms) step 5.
|
|
96
|
+
|
|
97
|
+
Optional: set the notification icon and channel name with the Android SDK's meta-data, described in its [Notifications](https://github.com/pushpilotai/pushpilot-android#notifications) section.
|
|
98
|
+
|
|
99
|
+
### iOS
|
|
100
|
+
|
|
101
|
+
1. **Give PushPilot your APNs key.** Create an APNs auth key (`.p8`) in your Apple Developer account and add it in the PushPilot dashboard as an APNs push project, with its Key ID and your Team ID. Create the iOS app on that project with your bundle id. The [iOS SDK README](https://github.com/pushpilotai/pushpilot-ios#integrate) has the exact steps. No Firebase is needed on iOS. If you keep React Native Firebase for Android only, you can drop it from iOS. List `@react-native-firebase/app` and `@react-native-firebase/messaging` with `platforms: { ios: null }` in `react-native.config.js`, as the example does.
|
|
102
|
+
2. **Turn on Push Notifications** in your app target: *Signing & Capabilities › + Capability › Push Notifications*.
|
|
103
|
+
3. **Hand PushPilot the device token** in your `AppDelegate`. This is the only native code PushPilot needs in the app:
|
|
104
|
+
|
|
105
|
+
```swift
|
|
106
|
+
import PushPilotReactNative
|
|
107
|
+
|
|
108
|
+
// in your AppDelegate class:
|
|
109
|
+
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
|
|
110
|
+
RNPushPilotBridge.setDeviceToken(deviceToken)
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
In an Objective-C `AppDelegate.mm`: `#import <PushPilotReactNative/PushPilotReactNative-Swift.h>` and `[RNPushPilotBridge setDeviceToken:deviceToken];` in the same method. Only the Swift form is built in this repo's example.
|
|
115
|
+
|
|
116
|
+
4. **Permission:** ask with whatever your app already uses (expo-notifications, React Native Firebase's `requestPermission`, or `UNUserNotificationCenter.requestAuthorization` in native code). You do not need to call `registerForRemoteNotifications`: the wrapper calls it at launch and each time the app becomes active, once notifications are allowed, so the token arrives as soon as the user says yes.
|
|
117
|
+
5. **Taps need no code.** At launch the wrapper joins the `UNUserNotificationCenter` delegate chain, as React Native Firebase and expo-notifications do. It records clicks on PushPilot pushes, opens their links or passes them to `setLinkHandler`, reports them to `setTapHandler`, and passes every call on, unchanged, to the delegate that was set before it. If your own code sets that delegate *after* launch, it replaces the wrapper's. In that case call `RNPushPilotBridge.handleNotificationResponse(response)` from your delegate's `didReceive`; it does all of the above.
|
|
118
|
+
6. **Optional: images and buttons**, with a [Notification Service Extension](#ios-notification-service-extension). Without one, PushPilot pushes arrive without them, and taps still work.
|
|
119
|
+
|
|
120
|
+
#### iOS Notification Service Extension
|
|
121
|
+
|
|
122
|
+
1. In Xcode, open `ios/<App>.xcworkspace` and choose **File › New › Target… › Notification Service Extension**. Name it, for example, `NotificationService`. Keep its bundle id under the app's (`<app bundle id>.NotificationService`), set its deployment target to iOS 15.1 (the app's) and its signing team to the app's. When Xcode asks whether to activate the new scheme, choose **Cancel** so you keep building the app's scheme.
|
|
123
|
+
2. Add the iOS SDK's package to the app's project: **File › Add Package Dependencies…**, enter the pushpilot-ios repository URL (while unpublished: **Add Local…** and pick your `pushpilot-ios` checkout), and add the **`PushPilotNotificationService`** library to the **extension target only**. Do not add `PushPilot` to the app target; the pod already brings it in.
|
|
124
|
+
3. Replace the generated `NotificationService.swift` with:
|
|
125
|
+
|
|
126
|
+
```swift
|
|
127
|
+
import PushPilotNotificationService
|
|
128
|
+
import UserNotifications
|
|
129
|
+
|
|
130
|
+
final class NotificationService: UNNotificationServiceExtension {
|
|
131
|
+
private let pushPilot = PushPilotServiceExtension()
|
|
132
|
+
|
|
133
|
+
override func didReceive(_ request: UNNotificationRequest,
|
|
134
|
+
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
|
|
135
|
+
if pushPilot.didReceive(request, withContentHandler: contentHandler) { return }
|
|
136
|
+
contentHandler(request.content) // not a PushPilot push: deliver it as is
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
override func serviceExtensionTimeWillExpire() {
|
|
140
|
+
pushPilot.serviceExtensionTimeWillExpire()
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
4. Nothing in the `Podfile`: the extension uses no pods. `pod install` keeps the target as it is.
|
|
146
|
+
|
|
147
|
+
The [iOS SDK README](https://github.com/pushpilotai/pushpilot-ios#images-and-buttons-notification-service-extension) explains what the helper does and how it fails safely. The example's `NotificationService` target is set up this way.
|
|
148
|
+
|
|
149
|
+
## Live activities
|
|
150
|
+
|
|
151
|
+
From 2.1.1, PushPilot can start, update and end live activities by push, from the dashboard, a campaign or the server API: a score, a delivery or an upload that stays on screen and changes with each update. The native SDKs do all the work; your app starts none itself and needs no JavaScript beyond the two optional calls below.
|
|
152
|
+
|
|
153
|
+
### Android
|
|
154
|
+
|
|
155
|
+
Nothing to add: the Android SDK 2.1.1 draws each live activity as one ongoing notification on a "Live updates" channel, from the same receiver that shows your other PushPilot pushes. On Android 16 an activity sent as promoted shows as a Live Update (status chip, segmented progress) when the user allows it; the SDK's manifest merges the `POST_PROMOTED_NOTIFICATIONS` permission it needs, a normal permission granted at install. Taps open the activity's link like a push's, through `setLinkHandler` when one is set. See the [Android SDK README](https://github.com/pushpilotai/pushpilot-android#live-activities).
|
|
156
|
+
|
|
157
|
+
### iOS
|
|
158
|
+
|
|
159
|
+
Live activities started by push need iOS 17.2 or later; the app itself still runs on iOS 15.1. In Xcode (`ios/<App>.xcworkspace`):
|
|
160
|
+
|
|
161
|
+
1. **Add a Widget Extension:** **File › New › Target… › Widget Extension**, named for example `LiveActivity`, with the template's *Include …* options unticked. Keep its bundle id under the app's, set its deployment target to iOS 16.1 or later and its signing team to the app's; choose **Cancel** when Xcode asks to activate the new scheme. Delete the generated widget files except the bundle.
|
|
162
|
+
2. **Add the `PushPilotLive` library to the extension target only**, from the pushpilot-ios package: if the app's project already has it (for the Notification Service Extension), pick the extension under *General › Frameworks and Libraries › +*; otherwise **File › Add Package Dependencies…** with the pushpilot-ios repository URL. The app target needs nothing: the wrapper's pod already brings in `PushPilot`, which includes `PushPilotLive`. Like the Notification Service Extension, the Widget Extension uses no pods, so nothing goes in the `Podfile`.
|
|
163
|
+
3. **Make the bundle return PushPilot's widget**, which draws every PushPilot layout on the Lock Screen and in the Dynamic Island:
|
|
164
|
+
|
|
165
|
+
```swift
|
|
166
|
+
import PushPilotLive
|
|
167
|
+
import SwiftUI
|
|
168
|
+
import WidgetKit
|
|
169
|
+
|
|
170
|
+
@main
|
|
171
|
+
struct LiveActivityWidgets: WidgetBundle {
|
|
172
|
+
var body: some Widget {
|
|
173
|
+
PushPilotLiveActivityWidget(appGroup: "group.com.example.app")
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
To draw activities your own way, return an `ActivityConfiguration(for: PushPilotLiveAttributes.self)` instead; see the [iOS SDK README](https://github.com/pushpilotai/pushpilot-ios#live-activities).
|
|
179
|
+
4. **Add `NSSupportsLiveActivities`** (Boolean, `YES`) to the app's `Info.plist`. Without it iOS starts none, and the SDK tells PushPilot so.
|
|
180
|
+
5. **Optional: an App Group** for images in layouts. Add the *App Groups* capability with the same group to the app and the extension, pass it to the widget as above and to `init`:
|
|
181
|
+
|
|
182
|
+
```tsx
|
|
183
|
+
PushPilot.init('pp_sdk_...', { appGroup: 'group.com.example.app' });
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
The SDK then downloads the layout's https images into the group for the widget. Without one, image blocks show their fallback icon.
|
|
187
|
+
6. **Pass opened URLs to `handleLiveActivityURL`.** A tap on a live activity opens your app with the activity's link plus a `pushpilot_live` marker. `handleLiveActivityURL` counts the click once and resolves to your link without the marker, or `null` when the activity has none:
|
|
188
|
+
|
|
189
|
+
```tsx
|
|
190
|
+
import { Linking } from 'react-native';
|
|
191
|
+
|
|
192
|
+
const opened = async (url: string | null) => {
|
|
193
|
+
if (!url) return;
|
|
194
|
+
const link = await PushPilot.handleLiveActivityURL(url);
|
|
195
|
+
if (link) router.open(link); // null: the tap only opens the app
|
|
196
|
+
};
|
|
197
|
+
Linking.getInitialURL().then(opened);
|
|
198
|
+
Linking.addEventListener('url', ({ url }) => opened(url));
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
`Linking` needs `RCTLinkingManager` in your `AppDelegate` or `SceneDelegate`, as React Native's [Linking guide](https://reactnative.dev/docs/linking) describes. Other URLs come back unchanged, so you can pass every URL through it. On Android it resolves every URL unchanged.
|
|
202
|
+
|
|
203
|
+
The SDK watches PushPilot activities while the app runs and reports their tokens and state to PushPilot. An Expo app that regenerates its `ios/` folder can only add a Widget Extension with a config plugin, which PushPilot does not provide.
|
|
204
|
+
|
|
205
|
+
## In-app messages
|
|
206
|
+
|
|
207
|
+
From 2.2.0, messages you publish in the dashboard's in-app section show over your app: a modal, full screen, bottom sheet, banner, card, carousel, or a coach mark pointing at one of your views. The native SDKs fetch, cache and draw them (an HTML page in a transparent web view over the current screen) and report `shown`, `clicked` and `dismissed`. See the [Android](https://github.com/pushpilotai/pushpilot-android#in-app-messages) and [iOS](https://github.com/pushpilotai/pushpilot-ios#in-app-messages) READMEs for how messages are fetched, cached and locked down.
|
|
208
|
+
|
|
209
|
+
1. **Nothing to add for app-open messages.** With `init` called at startup, the first eligible message with the "app open" trigger shows when the app comes to the foreground. Messages are fetched after the installation's first sync, at most once a minute on foreground, and show only from what is already cached, never from the network.
|
|
210
|
+
2. **Named moments.** For a message whose trigger is an in-app call, call `showInApp` with its name where it should appear:
|
|
211
|
+
|
|
212
|
+
```tsx
|
|
213
|
+
const shown = await PushPilot.showInApp('checkout');
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
It resolves to `true` when a message is now on screen, and `false` when none is cached and eligible, another message is showing, it is past its cap or outside its dates, or the SDK has not started. It never rejects. The call runs on the native main thread for you.
|
|
217
|
+
3. **Coach marks.** A coach-mark message points at one of your views by the name its target uses in the dashboard. Pass the view's `ref` once it is mounted:
|
|
218
|
+
|
|
219
|
+
```tsx
|
|
220
|
+
const compose = useRef<ComponentRef<typeof View>>(null);
|
|
221
|
+
useEffect(() => {
|
|
222
|
+
PushPilot.markView(compose, 'compose');
|
|
223
|
+
return () => PushPilot.unmarkView('compose');
|
|
224
|
+
}, []);
|
|
225
|
+
|
|
226
|
+
<View ref={compose} collapsable={false}>
|
|
227
|
+
<Button title="Compose" onPress={openComposer} />
|
|
228
|
+
</View>
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
- Give a plain `<View>` `collapsable={false}`: React Native removes layout-only views from the native tree, and a view with no native counterpart cannot be marked. Native components (`Pressable`, `TextInput`, `Image`...) need nothing extra.
|
|
232
|
+
- `markView` also takes a view tag from `findNodeHandle`. A ref that is not mounted yet logs a warning and marks nothing; mark it again from an effect or `onLayout`.
|
|
233
|
+
- The native view is looked up on the UI thread (New Architecture). The SDK holds it weakly; a later view with the same name replaces it, and `unmarkView(name)` forgets it. A coach mark shows only while its view is on screen; otherwise it waits.
|
|
234
|
+
4. **Links.** A button's link closes the message and goes to `setLinkHandler`, the same handler tapped pushes use ([Taps](#taps-on-android-and-ios)). Without one, the system opens it.
|
|
235
|
+
|
|
236
|
+
## Integrate (Expo development build)
|
|
237
|
+
|
|
238
|
+
PushPilot has no Expo config plugin. What works without one:
|
|
239
|
+
|
|
240
|
+
1. `npx expo install @pushpilotai/react-native`, then build a development build (`npx expo run:ios` / `npx expo run:android`, or `eas build --profile development`).
|
|
241
|
+
2. **Android:** the wrapper's receiver shows PushPilot pushes natively, as in a bare app; no Android code is needed. What the app still has to do is get FCM into the app (your `google-services.json`) and forward a push identifier with `setPushToken`. Either set up React Native Firebase with its config plugins, as its Expo instructions at [rnfirebase.io](https://rnfirebase.io) describe, and forward the FID or token as above, or use expo-notifications: on Android its `getDevicePushTokenAsync()` returns the FCM token. expo-notifications no longer shows PushPilot pushes a second time: it displays a data-only message by itself only when the data has a `title` or `message` key (checked in 58.1.9), and PushPilot's data now carries only `source` and `pushpilot`. While the app is in the foreground it still passes the message to your `setNotificationHandler`, so return no banner or list entry there when `PushPilot.handleMessage(notification.request.content.data)` is true. This repo does not build an Expo app, so the Expo steps are not verified here.
|
|
242
|
+
3. **iOS:** Expo regenerates the `AppDelegate`, so pass the token from JavaScript instead. expo-notifications gives the APNs token as hex, which `setPushToken` accepts on iOS:
|
|
243
|
+
|
|
244
|
+
```tsx
|
|
245
|
+
import * as Notifications from 'expo-notifications';
|
|
246
|
+
|
|
247
|
+
if (Platform.OS === 'ios') {
|
|
248
|
+
const { status } = await Notifications.requestPermissionsAsync();
|
|
249
|
+
if (status === 'granted') {
|
|
250
|
+
const { data } = await Notifications.getDevicePushTokenAsync(); // hex APNs token
|
|
251
|
+
PushPilot.setPushToken(data);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
Use `getDevicePushTokenAsync` (the APNs token), not `getExpoPushTokenAsync` (Expo's own token, which PushPilot cannot use). Call it at every launch once permission is granted, so a changed token reaches PushPilot. Turn on push notifications for the app (expo-notifications' config plugin adds the `aps-environment` entitlement). Taps need no code: expo-notifications 58 chains to the delegate that was set before it, as the wrapper does, so both libraries get every tap whichever starts first, and `setLinkHandler` and `setTapHandler` work as in a bare app. React Native Firebase's `getAPNSToken()` returns the same token in uppercase hex, which is also accepted.
|
|
257
|
+
4. **Images and buttons on iOS** need a Notification Service Extension target. An Expo app that regenerates its `ios/` folder can only add one with a config plugin, which PushPilot does not provide. Without it, PushPilot pushes still arrive and taps still work, without image or buttons.
|
|
258
|
+
|
|
259
|
+
## Android: how pushes reach the SDK
|
|
260
|
+
|
|
261
|
+
The wrapper declares its own receiver, `PushPilotMessageReceiver`, for the broadcast Google Play services sends for every FCM message (`com.google.android.c2dm.intent.RECEIVE`, guarded by the `com.google.android.c2dm.permission.SEND` permission). React Native Firebase uses the same kind of receiver. Every receiver for that broadcast gets each message: Firebase's own `FirebaseMessagingService` and React Native Firebase still get it, alongside the wrapper's.
|
|
262
|
+
|
|
263
|
+
For each data message the receiver builds the data map as FCM's `RemoteMessage.getData()` does. It leaves out FCM's own `google.*`, `gcm.*`, `from` and `collapse_key` keys and ignores deletion and send-status broadcasts. A PushPilot message's data is just `source` = `pushpilot` and `pushpilot`, a JSON string with the title, body, link, buttons and your `data`, which only the SDK reads. It then calls the Android SDK's `handleMessage` on a background thread, keeping the broadcast alive with `goAsync()` while the image downloads. For a PushPilot push (`source` = `pushpilot`) the SDK reports `delivered` and shows the notification; anything else is ignored.
|
|
264
|
+
|
|
265
|
+
A push, a notification tap or a button press can start a killed app's process with no JavaScript. The SDK then starts itself from the SDK key and `baseUrl` that the last `init` saved, so their `delivered` and `clicked` events are still sent. The wrapper keeps nothing of its own for that.
|
|
266
|
+
|
|
267
|
+
A second component, `PushPilotStartupProvider`, runs when the process starts, before your `Application.onCreate` and before the SDK handles a tap. If the last JavaScript run had a link handler, it installs the wrapper's link handler in the SDK, so the tap that launched a killed app reaches JavaScript's handler (see [Taps](#taps-on-android-and-ios)). It saves only that yes/no, in the app's preferences file `ai.pushpilot.reactnative`.
|
|
268
|
+
|
|
269
|
+
Why this way:
|
|
270
|
+
|
|
271
|
+
- **It works with or without React Native Firebase, and needs no Firebase dependency in the wrapper.** It also works with any other FCM library, and with your own native `FirebaseMessagingService`. Overriding the app's messaging service would clash with React Native Firebase, which declares its own. Calling from JavaScript (`onMessage`, `setBackgroundMessageHandler`) cannot show a push from a killed app reliably.
|
|
272
|
+
- **No app code.** Both components come from the library's manifest.
|
|
273
|
+
|
|
274
|
+
Limits:
|
|
275
|
+
|
|
276
|
+
- **Shown twice** if something else also displays PushPilot's data-only messages, such as your own `FirebaseMessagingService` calling the Android SDK's `handleMessage`. React Native Firebase does not display data-only messages, and expo-notifications displays them only when they have a `title` or `message` key, which PushPilot's do not.
|
|
277
|
+
- FCM can, rarely, deliver a message twice. Firebase's own service drops recent duplicates by message id; the wrapper's receiver does not.
|
|
278
|
+
|
|
279
|
+
## Taps on Android and iOS
|
|
280
|
+
|
|
281
|
+
`setLinkHandler` and `setTapHandler` behave the same on both platforms:
|
|
282
|
+
|
|
283
|
+
- **Which taps:** a tap on the push itself, or on a button with a link. Those open the app. A dismissal or a button without a link does not, and is not reported.
|
|
284
|
+
- **Order:** for a tap with a link, `setTapHandler` gets `{ notificationId, data }` first, then `setLinkHandler` gets the link.
|
|
285
|
+
- **Once:** each tap reaches each handler once, also after a JavaScript reload or when the app comes back to the foreground.
|
|
286
|
+
- **The tap that launched a killed app** waits until `init` and then goes to the handlers set before `init`. A handler set after `init` gets only later taps.
|
|
287
|
+
- **Without a link handler** the link opens through the system.
|
|
288
|
+
|
|
289
|
+
What differs underneath:
|
|
290
|
+
|
|
291
|
+
- **Android, without a link handler:** the SDK opens the link directly. If it is a web link, the browser opens and your app does not, so `setTapHandler` is not called for that tap. With a link handler set, your launcher activity opens first, then the link goes to JavaScript.
|
|
292
|
+
- **Android, adding a link handler in an app update:** the startup provider installs the native link handler only if the previous JavaScript run had one. So on the very first cold start after the update, a tap's link opens in the system. Later taps reach your handler.
|
|
293
|
+
- **iOS** always opens the app for these taps. Without a link handler, iOS then opens the link.
|
|
294
|
+
|
|
295
|
+
The link handler and tap data come from the native SDKs' own APIs (`setLinkHandler` and `tappedNotification` on Android, `setLinkHandler` and `userInfo["data"]` on iOS).
|
|
296
|
+
|
|
297
|
+
## Upgrading from 1.x
|
|
298
|
+
|
|
299
|
+
- **iOS no longer uses Firebase.** `setPushToken` on iOS now takes the APNs device token as hex. An FCM token or FID passed on iOS, the 1.x path, is ignored with a warning, so a 1.x app keeps the last token the SDK stored until you switch. Switch by adding the `AppDelegate` method above (or, on Expo, passing `getDevicePushTokenAsync`), and by giving PushPilot your APNs key.
|
|
300
|
+
- **Android pushes are shown for you.** If your 1.x app showed PushPilot pushes itself after `handleMessage` returned `true`, remove that code, or they appear twice.
|
|
301
|
+
- **New:** `setLinkHandler` and `setTapHandler`, on both platforms ([Taps](#taps-on-android-and-ios)).
|
|
302
|
+
- **2.1.1:** [live activities](#live-activities), with `init`'s `appGroup` and `handleLiveActivityURL`. Nothing changes for apps that do not use them.
|
|
303
|
+
- **2.2.0:** [in-app messages](#in-app-messages), with `showInApp`, `markView` and `unmarkView`. App-open messages show with no code; their links reach your existing `setLinkHandler`.
|
|
304
|
+
- Every other call is unchanged, including `init`'s `baseUrl`.
|
|
305
|
+
|
|
306
|
+
## API
|
|
307
|
+
|
|
308
|
+
```tsx
|
|
309
|
+
import PushPilot, {
|
|
310
|
+
type AttributeValue,
|
|
311
|
+
type InitOptions,
|
|
312
|
+
type TappedNotification,
|
|
313
|
+
} from '@pushpilotai/react-native';
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
| Call | What it does |
|
|
317
|
+
|---|---|
|
|
318
|
+
| `init(sdkKey, { baseUrl?, appGroup? })` | Starts the SDK with your public SDK key. Call once at startup; later calls are ignored (including after a JavaScript reload). `baseUrl` defaults to `https://pushpilot.ai`; set it only for a self-hosted server. The native SDKs save the values, so a process started by a push or a tap before JavaScript runs can still send its events. `appGroup` (iOS) is the App Group shared with your Widget Extension, for images in [live activities](#live-activities); Android ignores it. |
|
|
319
|
+
| `setPushToken(token \| null)` | Stores the push identifier and syncs it. **Android:** the Firebase Installation ID from `register` / `onRegistered`, or the FCM token from `getToken` / `onTokenRefresh` where your Firebase library has no FID API; pass only one kind. **iOS:** the APNs device token as hex (`getDevicePushTokenAsync`, `getAPNSToken`), if you do not forward it from the `AppDelegate`; anything else is ignored with a warning. `null` clears it, and the device then stops receiving pushes. |
|
|
320
|
+
| `setExternalUserId(id \| null)` | Links this installation to your own user id (1 to 255 characters). One user can have many installations. `null` clears it, like `logout()`. |
|
|
321
|
+
| `setAttributes(record)` | Merges custom attributes. Values are strings, numbers or booleans; pass dates as RFC 3339 strings (`date.toISOString()`) and `null` to remove an attribute. Only attributes declared in the dashboard are stored. |
|
|
322
|
+
| `setTopics(list)` | Replaces the topic list (at most 100; letters, digits and `-_.~%`). Invalid names are dropped. |
|
|
323
|
+
| `logout()` | Clears the external user id. The device stays registered and keeps receiving pushes. |
|
|
324
|
+
| `forget()` | Deletes this installation from PushPilot and clears all local SDK state. A new installation is registered after your next PushPilot call or the next app launch. Use it in your account-deletion or privacy flow. |
|
|
325
|
+
| `handleMessage(data): boolean` | `true` when a received push's data has `source` equal to `pushpilot`. Answered in JavaScript with the native SDKs' rule; makes no native or network call. Use it to skip PushPilot pushes in your own message handlers. |
|
|
326
|
+
| `setLinkHandler(handler \| null)` | Receives the link (`string`) of each tapped PushPilot push instead of the system opening it, like the native SDKs' `setLinkHandler`. A new handler replaces the old one; `null` lets the system open links again. Set it before `init` to get the tap that launched the app. See [Taps](#taps-on-android-and-ios). |
|
|
327
|
+
| `handleLiveActivityURL(url): Promise<string \| null>` | For a URL your app was opened with: a tap on an iOS live activity is counted once and resolves to the activity's own link without PushPilot's marker, or `null` when it has none. Any other URL, and every URL on Android, resolves unchanged. Never rejects. See [Live activities](#live-activities). |
|
|
328
|
+
| `showInApp(name): Promise<boolean>` | Shows the first eligible cached [in-app message](#in-app-messages) whose trigger is `name`; resolves to whether one is now on screen. No network call. Never rejects. |
|
|
329
|
+
| `markView(ref \| viewTag, name)` | Names a mounted view (a `ref` or a `findNodeHandle` tag) for coach-mark messages whose target is `name`. A plain `<View>` needs `collapsable={false}`. A later view with the same name replaces it. |
|
|
330
|
+
| `unmarkView(name)` | Forgets the view marked with `name`. |
|
|
331
|
+
| `setTapHandler(handler \| null)` | Receives a `TappedNotification`, `{ notificationId: string, data: Record<string, string> }`, for each tapped PushPilot push that opens the app. `data` is the push's custom data, empty when it has none. A new handler replaces the old one; `null` stops it. Set it before `init` to get the tap that launched the app. |
|
|
332
|
+
|
|
333
|
+
Native, for the iOS `AppDelegate` (`import PushPilotReactNative`):
|
|
334
|
+
|
|
335
|
+
| Call | What it does |
|
|
336
|
+
|---|---|
|
|
337
|
+
| `RNPushPilotBridge.setDeviceToken(_ deviceToken: Data)` | Passes the APNs device token from `didRegisterForRemoteNotificationsWithDeviceToken`. |
|
|
338
|
+
| `RNPushPilotBridge.handleNotificationResponse(_ response) -> Bool` | Only when your own `UNUserNotificationCenter` delegate replaces the wrapper's after launch: call it from that delegate's `didReceive`. It records the click and feeds `setLinkHandler` and `setTapHandler`. `false` for pushes that are not from PushPilot. |
|
|
339
|
+
|
|
340
|
+
Invalid values are dropped by the native SDK with a log message instead of being sent. Native logs appear under the `PushPilot` tag in Logcat and the `ai.pushpilot.sdk` subsystem in the iOS console; the SDK key and push token are never logged.
|
|
341
|
+
|
|
342
|
+
## What is sent, and store declarations
|
|
343
|
+
|
|
344
|
+
The data each sync carries, the `delivered` (Android) and `clicked` (both) events, when requests are made, and what to declare in Google Play's Data safety form and App Store Connect's App Privacy section are the same as for the native SDKs. The wrapper sends nothing of its own. See the [Android SDK README](https://github.com/pushpilotai/pushpilot-android#what-the-sdk-sends-and-when) and the [iOS SDK README](https://github.com/pushpilotai/pushpilot-ios#what-the-sdk-sends-and-when).
|
|
345
|
+
|
|
346
|
+
## Example app
|
|
347
|
+
|
|
348
|
+
`example/`:
|
|
349
|
+
|
|
350
|
+
- Initialises PushPilot at startup and sets a tap handler and a link handler before `init`. It shows the last tapped push's id and data, or its link.
|
|
351
|
+
- **Android:** forwards the Firebase Installation ID from `@react-native-firebase/messaging` (`register` and `onRegistered`, turned on in `example/firebase.json`), and has a permission button.
|
|
352
|
+
- **iOS:** no Firebase (`example/react-native.config.js` keeps React Native Firebase off iOS). The `AppDelegate` asks for permission at launch and forwards the device token, and the app has the Push Notifications entitlement and a `NotificationService` extension target.
|
|
353
|
+
- **Live activities:** `init` passes the App Group `group.pushpilot.reactnative.example`, and every URL the app is opened with goes through `handleLiveActivityURL`; the screen shows the link that comes back. On iOS the app has `NSSupportsLiveActivities`, the App Group, and a `LiveActivity` Widget Extension target (`example/ios/LiveActivity/`) that returns `PushPilotLiveActivityWidget` and links `PushPilotLive` from the pushpilot-ios package.
|
|
354
|
+
- **In-app messages:** a **Show in-app** button calls `showInApp('checkout')` and shows the result; the button is marked as the coach-mark target `example-button`.
|
|
355
|
+
- Buttons for set user id, set topics, logout and forget.
|
|
356
|
+
|
|
357
|
+
```bash
|
|
358
|
+
yarn
|
|
359
|
+
yarn example start # Metro
|
|
360
|
+
yarn example android # or: yarn example ios
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
It builds and runs without any Firebase config; Android then has no push identifier. To receive real pushes:
|
|
364
|
+
|
|
365
|
+
- Put your SDK key in `PUSHPILOT_SDK_KEY` in `example/src/App.tsx`.
|
|
366
|
+
- Android: add your own `example/android/app/google-services.json`. It is git-ignored; never commit it. The build applies the Google Services plugin only when the file exists.
|
|
367
|
+
- iOS: set your signing team, bundle ids and an App Group you own on all three targets, and give PushPilot the matching APNs key. The extensions' bundle ids must start with the app's.
|
|
368
|
+
|
|
369
|
+
On the iOS simulator you can try taps without a server:
|
|
370
|
+
|
|
371
|
+
```bash
|
|
372
|
+
xcrun simctl push booted pushpilot.reactnative.example push.json
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
Here `push.json` is `{"aps":{"alert":{"title":"Hi","body":"Tap me"}},"source":"pushpilot","notification_id":"<any uuid>","url":"https://example.com","data":{"order_id":"42"}}`. Tapping it, even with the app killed, records a click and reports the tap and then the link; the screen shows the link, the last of the two. Use a new `notification_id` for each try: each one is reported once per app process. `simctl push` does not run the extension, so image and buttons need a real push.
|
|
376
|
+
|
|
377
|
+
## Local development
|
|
378
|
+
|
|
379
|
+
This repo and its example use the published native SDKs: `ai.pushpilot:sdk` from Maven Central and `https://github.com/pushpilotai/pushpilot-ios` from its tags. To work against unreleased changes in the native SDKs, check them out beside this repo:
|
|
380
|
+
|
|
381
|
+
```
|
|
382
|
+
pushpilot-sdks/
|
|
383
|
+
pushpilot-android/
|
|
384
|
+
pushpilot-ios/
|
|
385
|
+
pushpilot-react-native/
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
and switch these three places locally (don't commit them):
|
|
389
|
+
|
|
390
|
+
1. **Android:** `cd ../pushpilot-android && ./gradlew :sdk:publishToMavenLocal`, then add `allprojects { repositories { mavenLocal { content { includeGroup("ai.pushpilot") } } } }` to `example/android/build.gradle` (or another app's root `build.gradle`).
|
|
391
|
+
2. **iOS:** in `PushPilotReactNative.podspec`, set the `spm_dependency` `url:` to the absolute path of your `pushpilot-ios` checkout. Local paths need React Native 0.84 or later; on 0.81 to 0.83 use `"file:///absolute/path/to/pushpilot-ios"` with `requirement: { kind: "branch", branch: "<branch>" }`, which builds the committed branch, not uncommitted edits.
|
|
392
|
+
3. **The example's extensions** (Notification Service and Live Activity, which share one package reference): in Xcode, replace the `pushpilot-ios` package under *Package Dependencies* with *Add Local…* and the checkout.
|
|
393
|
+
|
|
394
|
+
### Checks
|
|
395
|
+
|
|
396
|
+
```bash
|
|
397
|
+
yarn typecheck
|
|
398
|
+
yarn lint
|
|
399
|
+
yarn test # Jest: the JavaScript layer, with the native module mocked
|
|
400
|
+
yarn test:ios # the iOS APNs-hex parser, compiled with swiftc (macOS)
|
|
401
|
+
cd example/android && ./gradlew :pushpilotai_react-native:testDebugUnitTest # the Android receiver's data filter
|
|
402
|
+
```
|
|
403
|
+
|
|
404
|
+
## Releasing
|
|
405
|
+
|
|
406
|
+
See [RELEASING.md](RELEASING.md) and [CHANGELOG.md](CHANGELOG.md).
|
|
407
|
+
|
|
408
|
+
## Licence
|
|
409
|
+
|
|
410
|
+
Apache License 2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
ext.PushPilotReactNative = [
|
|
2
|
+
minSdkVersion: 24,
|
|
3
|
+
compileSdkVersion: 36
|
|
4
|
+
]
|
|
5
|
+
|
|
6
|
+
ext.getExtOrDefault = { prop ->
|
|
7
|
+
if (rootProject.ext.has(prop)) {
|
|
8
|
+
return rootProject.ext.get(prop)
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
return PushPilotReactNative[prop]
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
apply plugin: "com.android.library"
|
|
16
|
+
|
|
17
|
+
if (project.extensions.findByName("kotlin") == null) {
|
|
18
|
+
apply plugin: "kotlin-android"
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
apply plugin: "com.facebook.react"
|
|
23
|
+
|
|
24
|
+
android {
|
|
25
|
+
namespace "ai.pushpilot.reactnative"
|
|
26
|
+
|
|
27
|
+
compileSdkVersion getExtOrDefault("compileSdkVersion")
|
|
28
|
+
|
|
29
|
+
defaultConfig {
|
|
30
|
+
minSdkVersion getExtOrDefault("minSdkVersion")
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
dependencies {
|
|
35
|
+
implementation "com.facebook.react:react-android"
|
|
36
|
+
implementation "ai.pushpilot:sdk:2.2.0"
|
|
37
|
+
testImplementation "junit:junit:4.13.2"
|
|
38
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
|
2
|
+
|
|
3
|
+
<application>
|
|
4
|
+
<!--
|
|
5
|
+
Gets every FCM message from Google Play services, as React Native Firebase's own receiver
|
|
6
|
+
does, so PushPilot pushes are shown even when the app is killed and no JavaScript runs.
|
|
7
|
+
Coexists with the app's own FirebaseMessagingService: both receive each message.
|
|
8
|
+
-->
|
|
9
|
+
<receiver
|
|
10
|
+
android:name=".PushPilotMessageReceiver"
|
|
11
|
+
android:exported="true"
|
|
12
|
+
android:permission="com.google.android.c2dm.permission.SEND">
|
|
13
|
+
<intent-filter>
|
|
14
|
+
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
|
|
15
|
+
</intent-filter>
|
|
16
|
+
</receiver>
|
|
17
|
+
|
|
18
|
+
<!-- Installs the link handler at process start, before the SDK handles the tap that launched a killed app. -->
|
|
19
|
+
<provider
|
|
20
|
+
android:name=".PushPilotStartupProvider"
|
|
21
|
+
android:authorities="${applicationId}.pushpilot-startup"
|
|
22
|
+
android:exported="false" />
|
|
23
|
+
</application>
|
|
24
|
+
</manifest>
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
package ai.pushpilot.reactnative
|
|
2
|
+
|
|
3
|
+
import ai.pushpilot.sdk.PushPilot
|
|
4
|
+
import android.content.BroadcastReceiver
|
|
5
|
+
import android.content.Context
|
|
6
|
+
import android.content.Intent
|
|
7
|
+
|
|
8
|
+
/** Hands every FCM data message to the native SDK, which shows PushPilot pushes and ignores the rest. */
|
|
9
|
+
class PushPilotMessageReceiver : BroadcastReceiver() {
|
|
10
|
+
|
|
11
|
+
/** Runs `handleMessage` off the main thread, keeping the broadcast alive while the image downloads. */
|
|
12
|
+
override fun onReceive(context: Context, intent: Intent) {
|
|
13
|
+
val bundle = intent.extras ?: return
|
|
14
|
+
@Suppress("DEPRECATION") // Bundle.get is the only untyped getter; FCM's data values are all strings.
|
|
15
|
+
val data = messageData(bundle.keySet().associateWith { bundle.get(it) }) ?: return
|
|
16
|
+
val app = context.applicationContext
|
|
17
|
+
val pending = goAsync()
|
|
18
|
+
Thread {
|
|
19
|
+
try {
|
|
20
|
+
PushPilot.handleMessage(app, data)
|
|
21
|
+
} catch (e: Exception) {
|
|
22
|
+
// The SDK catches its own errors; this only keeps an unexpected one from killing the process.
|
|
23
|
+
} finally {
|
|
24
|
+
pending.finish()
|
|
25
|
+
}
|
|
26
|
+
}.start()
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
companion object {
|
|
30
|
+
private val FCM_KEYS = setOf("from", "message_type", "collapse_key")
|
|
31
|
+
|
|
32
|
+
/** The message's data, as FCM's `RemoteMessage.getData()` builds it; null for deletion and send-status broadcasts. */
|
|
33
|
+
@JvmStatic
|
|
34
|
+
fun messageData(extras: Map<String, Any?>): Map<String, String>? {
|
|
35
|
+
if ((extras["message_type"] as? String ?: "gcm") != "gcm") return null
|
|
36
|
+
return extras.entries
|
|
37
|
+
.filter { (key, _) -> !key.startsWith("google.") && !key.startsWith("gcm.") && key !in FCM_KEYS }
|
|
38
|
+
.mapNotNull { (key, value) -> (value as? String)?.let { key to it } }
|
|
39
|
+
.toMap()
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|