Skip to content

Commit bf5467b

Browse files
[CHNL-5370] Updating readme to include instructions on how to use initialize and setToken from RN code. (#113)
* 0.1.1 * added troubleshooting * updated readme with initilize and set token instructions * adding notifee stuff to trouble shooting guide * removed duplicate android * removed package.json * some minor fixes * added example on requesting permission * Apply suggestions from code review Co-authored-by: Evan C Masseau <[email protected]> * minor updates * review comments * updated readme --------- Co-authored-by: Evan C Masseau <[email protected]>
1 parent a44a582 commit bf5467b

File tree

2 files changed

+134
-9
lines changed

2 files changed

+134
-9
lines changed

Diff for: README.md

+127-9
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
- [Android](#android-1)
1818
- [iOS](#ios-1)
1919
- [Initialization](#initialization)
20+
- [React Native Initialization](#react-native-initialization)
21+
- [Native Initialization](#native-initialization)
2022
- [Identifying a Profile](#identifying-a-profile)
2123
- [Reset Profile](#reset-profile)
2224
- [Anonymous Tracking](#anonymous-tracking)
@@ -25,6 +27,8 @@
2527
- [Prerequisites](#prerequisites)
2628
- [Setup](#setup)
2729
- [Collecting Push Tokens](#collecting-push-tokens)
30+
- [React Native Token Collection](#react-native-token-collection)
31+
- [Native Token Collection](#native-token-collection)
2832
- [Receiving Push Notifications](#receiving-push-notifications)
2933
- [Rich Push](#rich-push)
3034
- [Tracking Open Events](#tracking-open-events)
@@ -82,9 +86,11 @@ yarn add klaviyo-react-native-sdk
8286
```
8387

8488
### Example App
89+
8590
We have included a bare-bones example app in this repository for reference of how to integrate with our SDK.
8691
It is primarily intended to give code samples such as how and where to `initialize` or how to implement notification
8792
delegate methods on iOS. To actually run the example app:
93+
8894
- Clone this repository
8995
- From the root directory, run `yarn example-setup`. This is an alias that will do the following:
9096
- Run `yarn install --immutable` from the root directory
@@ -127,10 +133,28 @@ pod install
127133

128134
## Initialization
129135

130-
The SDK must be initialized with the short alphanumeric
131-
[public API key](https://help.klaviyo.com/hc/en-us/articles/115005062267#difference-between-public-and-private-api-keys1)
132-
for your Klaviyo account, also known as your Site ID. Initialization is done in the native layer, and must occur before
133-
any other SDK methods can be invoked. Follow the native SDK instructions for initialization, and refer to the
136+
The SDK must be initialized with the short alphanumeric [public API key](https://help.klaviyo.com/hc/en-us/articles/115005062267#difference-between-public-and-private-api-keys1)
137+
for your Klaviyo account, also known as your Site ID.
138+
139+
Initialize _must_ be called prior to invoking any other SDK methods so that Klaviyo SDK can track profiles, events and push tokens toward the correct Klaviyo account.
140+
Any SDK operations invoked before initialize will be dropped, and result in a logged error.
141+
142+
You can call `initialize` from your app's React Native layer or from the platform-specific native code.
143+
This decision is dependent on your app's architecture. It is not required to initialize the SDK in both places!
144+
Note: It is safe to re-initialize, e.g. if your app needs to connect to more than one Klaviyo account.
145+
146+
### React Native Initialization
147+
148+
Below is an example of how to initialize the SDK from your React Native code:
149+
150+
```typescript
151+
import { Klaviyo } from 'klaviyo-react-native-sdk';
152+
Klaviyo.initialize('YOUR_KLAVIYO_PUBLIC_API_KEY');
153+
```
154+
155+
### Native Initialization
156+
157+
Follow the native SDK instructions for initialization, and refer to the
134158
[example app](./example) in this repository for guidance:
135159

136160
- [Android SDK instructions](https://github.com/klaviyo/klaviyo-android-sdk#Initialization), and
@@ -253,17 +277,111 @@ Refer to the following README sections on push setup:
253277

254278
### Collecting Push Tokens
255279

256-
Push tokens must be collected in the native layer. Follow the platform-specific instructions below:
280+
Push tokens can be collected either from your app's react native code or in the native code. Below sections discuss both approaches, and
281+
you are free to pick one that best suits your app's architecture. Note that doing this in one location is sufficient.
282+
283+
#### React Native Token Collection
284+
285+
In order to collect the APNs push token in your React Native code you need to:
286+
287+
1. Import a library such as [`@react-native-firebase/messaging`](https://www.npmjs.com/package/@react-native-firebase/messaging) to your react native project. The below instructions are specific for `@react-native-firebase/messaging` library.
288+
2. Import Firebase iOS SDK to your iOS project. Setup instructions can be found [here](https://firebase.google.com/docs/ios/setup).
289+
3. In order for the `UNUserNotificationCenter` delegate methods to be called in `AppDelegate`, method swizzling should be disabled for the Firebase SDK. For more information on this,
290+
please refer to the [Firebase documentation](https://firebase.google.com/docs/cloud-messaging/ios/client). Disabling method swizzling be done by adding the following to your `Info.plist`:
291+
292+
```xml
293+
<key>FirebaseAppDelegateProxyEnabled</key>
294+
<false/>
295+
```
296+
297+
4. In `application:didRegisterForRemoteNotificationsWithDeviceToken:` method in your `AppDelegate.m` file, you can add the following code to set the push token to the firebase SDK:
298+
299+
```objective-c
300+
// since we disbaled swizzling, we have to manually set this
301+
FIRMessaging.messaging.APNSToken = deviceToken;
302+
```
303+
304+
5. Finally, in your React Native code, you can collect & set the push token as follows:
305+
306+
```typescript
307+
import messaging from '@react-native-firebase/messaging';
308+
import { Klaviyo } from 'klaviyo-react-native-sdk';
309+
import { Platform } from 'react-native';
310+
311+
const fetchAndSetPushToken = async () => {
312+
try {
313+
let deviceToken: string | null = null;
314+
if (Platform.OS === 'android') {
315+
deviceToken = await messaging().getToken();
316+
console.log('FCM Token:', deviceToken);
317+
} else {
318+
deviceToken = await messaging().getAPNSToken();
319+
console.log('APNs Token:', deviceToken);
320+
}
321+
322+
if (deviceToken != null && deviceToken.length > 0) {
323+
Klaviyo.setPushToken(deviceToken!);
324+
}
325+
} catch (error) {
326+
console.error('Error in fetchAndSetPushToken:', error);
327+
}
328+
};
329+
```
330+
331+
For android token collection, there isn't any additional setup required on the native side. The above code should work as is.
332+
333+
#### Native Token Collection
334+
335+
Follow the platform-specific instructions below:
257336

258337
- [Android](https://github.com/klaviyo/klaviyo-android-sdk#Collecting-Push-Tokens)
259338
- [iOS](https://github.com/klaviyo/klaviyo-swift-sdk#Collecting-Push-Tokens)
260339

261340
#### Notification Permission
262341

263-
Requesting user permission to display notifications can be managed in the native layer as instructed in our native SDK
264-
documentation, or with a third party library that provides cross-platform permissions APIs. If you opt for a
265-
cross-platform permission solution, you will still need to provide the Klaviyo SDK with the push token from the
266-
native layer after a permission change.
342+
Requesting user permission to display notifications can be managed in:
343+
344+
1. The native layer as instructed in our native SDK documentation,
345+
346+
- [Android](https://github.com/klaviyo/klaviyo-android-sdk#collecting-push-tokens)
347+
- [iOS](https://github.com/klaviyo/klaviyo-swift-sdk?tab=readme-ov-file#request-push-notification-permission)
348+
349+
If you requested permission using native code then continue using Klaviyo's native platform SDKs `setToken` method to inform the SDK of permission change.
350+
351+
2. Leveraging a third party library that provides cross-platform permissions APIs like firebase [`react-native-firebase/messaging`](https://www.npmjs.com/package/@react-native-firebase/messaging). If you opt for a
352+
cross-platform permission solution, you can now call the Klaviyo's react native SDK's `setToken` method to refresh the token's enablement status.
353+
354+
Below is an example of how to use `@react-native-firebase/messaging` to request permission and set the token:
355+
356+
```typescript
357+
import messaging from '@react-native-firebase/messaging';
358+
359+
const requestUserPermission = async () => {
360+
let isAuthorized = false;
361+
362+
if (Platform.OS === 'android') {
363+
const androidAuthStatus = await PermissionsAndroid.request(
364+
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
365+
);
366+
isAuthorized = androidAuthStatus === 'granted';
367+
} else if (Platform.OS === 'ios') {
368+
const iOsAuthStatus = await messaging().requestPermission();
369+
isAuthorized =
370+
iOsAuthStatus === messaging.AuthorizationStatus.AUTHORIZED ||
371+
iOsAuthStatus === messaging.AuthorizationStatus.PROVISIONAL;
372+
}
373+
374+
// refer the `fetchAndSetPushToken` method from the previous section for how to get and set the push token
375+
376+
if (isAuthorized) {
377+
console.log('User has notification permissions enabled.');
378+
} else {
379+
console.log('User has notification permissions disabled');
380+
}
381+
};
382+
```
383+
384+
Note that either one of the above approaches is sufficient to inform the Klaviyo SDK of the permission change.
267385

268386
### Receiving Push Notifications
269387

Diff for: Troubeshooting.md

+7
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,10 @@
3939

4040
2. If the command `pod install` is outputting version mismatch errors for `KlaviyoSwift`, please run `pod update KlaviyoSwift`
4141
as indicated in the error message to update your local pods spec repo.
42+
43+
### `UNUserNotificationCenter` delegate methods not being called
44+
45+
If you are not seeing the delegate methods for `UNUserNotificationCenter` being called in `AppDelegate`, there are two possible reasons for this,
46+
47+
1. [Notifee](https://notifee.app/) intercepts the AppDelegate delegate methods and hence you may not receive the delegate calls if notifee is included in the iOS project. The solution is to remove notifee dependency from your project or exclude it for iOS.
48+
2. Firebase iOS SDK also swizzles AppDelegate methods when configured on your iOS app. If after disabling notifee, if the delegates are still not called, this may be the reason. Method swizzling can be turned off by following [Firebase's documentation](https://firebase.google.com/docs/cloud-messaging/ios/client).

0 commit comments

Comments
 (0)