Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,11 @@ If you are running iOS SDK [v19.5.6](https://github.com/intercom/intercom-ios/re
- [Manual linking (React Native <=0.59)](#ios-manual-linking-with-react-native-v059-and-below)
- [Setup](#ios-setup)
- [Permissions](#ios-permissions)
- [Location permission in Mobile Carousels](#ios-location-permission-in-mobile-carousels)
- [Push Notifications](#ios-push-notifications)
- [Push notification deep links support](#ios-push-notification-deep-links-support)
- [Expo](#expo)
- [iOS location permission in Mobile Carousels](#expo-ios-location-permission-in-mobile-carousels)
- [Push Notifications](#expo-push-notifications)
- [Push notification deep links support](#expo-push-notification-deep-links-support)
- [Android](#android-deep-link)
Expand Down Expand Up @@ -413,6 +415,52 @@ Add these permissions to your `Info.plist`:

**Note:** These permissions are only requested when the user attempts to use the respective feature. You can customize the description strings to match your app's use case.

#### iOS: Location permission in Mobile Carousels

Intercom doesn't use CoreLocation itself, so your app doesn't need a location purpose string just because it includes Intercom. Mobile Carousel screens that ask for location permission are only shown on iOS once your app gives Intercom a location permission provider. Android needs no extra setup.

To show those screens, add `NSLocationWhenInUseUsageDescription` to your `Info.plist` (and `NSLocationAlwaysAndWhenInUseUsageDescription` if a carousel asks for "Always" access), then add a provider to your `AppDelegate.swift`:

```Swift
import CoreLocation
import Intercom

final class IntercomLocationPermissionProvider: NSObject, ICMLocationPermissionProvider, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()

var authorizationStatusDidChange: ((ICMLocationAuthorizationStatus) -> Void)?

override init() {
super.init()
locationManager.delegate = self
}

func currentAuthorizationStatus() -> ICMLocationAuthorizationStatus {
ICMLocationAuthorizationStatus(rawValue: Int(locationManager.authorizationStatus.rawValue)) ?? .notDetermined
}

func requestWhenInUsePermission() {
locationManager.requestWhenInUseAuthorization()
}

func requestAlwaysPermission() {
locationManager.requestAlwaysAuthorization()
}

func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
authorizationStatusDidChange?(currentAuthorizationStatus())
}
}
```

and register it inside `didFinishLaunchingWithOptions`:

```Swift
Intercom.setLocationPermissionProvider(IntercomLocationPermissionProvider())
```

If you use Expo, set the [`iosLocationPermission`](#expo-ios-location-permission-in-mobile-carousels) plugin option instead.

#### iOS: Push Notifications

> **Note**: You should request user permission to display push notifications.
Expand Down Expand Up @@ -537,6 +585,7 @@ The plugin provides props for extra customization. Every time you change the pro
- `iosApiKey` (_string_): iOS API Key from Intercom.
- `intercomRegion` (_string_): Region for Intercom `US`, `EU`, `AU`. Optional. Defaults to `US`.
- `useManualInit` (_boolean_): Set to `true` to manually initialize Intercom from JavaScript instead of at app startup. Optional. Defaults to `false`.
- `iosLocationPermission` (_boolean_): Set to `true` to show Mobile Carousel screens that ask for location permission on iOS. See [Expo: iOS location permission in Mobile Carousels](#expo-ios-location-permission-in-mobile-carousels). Optional. Defaults to `false`.

```json
{
Expand Down Expand Up @@ -612,6 +661,33 @@ To enable camera and microphone features in your Expo app, add the following to

After adding these permissions, run `npx expo prebuild` to regenerate the native iOS project with the updated Info.plist.

#### Expo: iOS location permission in Mobile Carousels

Mobile Carousel screens that ask for location permission are only shown on iOS once your app gives Intercom a location permission provider. Set `iosLocationPermission` to `true` and the plugin adds one to your `AppDelegate`. Add the location purpose strings too:

```json
{
"expo": {
"ios": {
"infoPlist": {
"NSLocationWhenInUseUsageDescription": "Share your location when a message asks for it",
"NSLocationAlwaysAndWhenInUseUsageDescription": "Share your location when a message asks for it"
}
},
"plugins": [
[
"@intercom/intercom-react-native",
{
"iosLocationPermission": true
}
]
]
}
}
```

`NSLocationAlwaysAndWhenInUseUsageDescription` is only needed if a carousel asks for "Always" access. Android needs no extra setup.

#### Expo: Push notifications

Add the following configurations into your `app.json` or `app.config.js`:
Expand Down
107 changes: 107 additions & 0 deletions __tests__/withIosLocationPermission.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { updateAppDelegateLocationPermission } from '../src/expo-plugins/withIosLocationPermission';

const swiftAppDelegate = `import Expo
import React
import ReactAppDependencyProvider

@UIApplicationMain
public class AppDelegate: ExpoAppDelegate {
var window: UIWindow?

public override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
let delegate = ReactNativeDelegate()
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
`;

const objcAppDelegate = `#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.moduleName = @"main";
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

@end
`;

const swiftRegistration =
'Intercom.setLocationPermissionProvider(IntercomLocationPermissionProvider())';
const objcRegistration =
'[Intercom setLocationPermissionProvider:[IntercomLocationPermissionProvider new]];';

const occurrences = (haystack: string, needle: string) =>
haystack.split(needle).length - 1;

describe('updateAppDelegateLocationPermission', () => {
it('adds the Swift provider before the app delegate and registers it before the launch return', () => {
const result = updateAppDelegateLocationPermission(
swiftAppDelegate,
'swift',
true
);

expect(
result.indexOf('final class IntercomLocationPermissionProvider')
).toBeLessThan(result.indexOf('@UIApplicationMain'));
expect(result.indexOf(swiftRegistration)).toBeLessThan(
result.indexOf('return super.application')
);
expect(result.indexOf(swiftRegistration)).toBeGreaterThan(
result.indexOf('let delegate = ReactNativeDelegate()')
);
});

it('adds the Objective-C provider before @implementation AppDelegate and registers it', () => {
const result = updateAppDelegateLocationPermission(
objcAppDelegate,
'objcpp',
true
);

expect(
result.indexOf('@implementation IntercomLocationPermissionProvider')
).toBeLessThan(result.indexOf('@implementation AppDelegate'));
expect(result.indexOf(objcRegistration)).toBeLessThan(
result.indexOf('return [super application')
);
});

it('does not duplicate code when run again', () => {
const once = updateAppDelegateLocationPermission(
swiftAppDelegate,
'swift',
true
);
const twice = updateAppDelegateLocationPermission(once, 'swift', true);

expect(twice).toEqual(once);
expect(occurrences(twice, swiftRegistration)).toBe(1);
});

it('removes previously generated code when disabled', () => {
const enabled = updateAppDelegateLocationPermission(
objcAppDelegate,
'objcpp',
true
);

expect(
updateAppDelegateLocationPermission(enabled, 'objcpp', false)
).toEqual(objcAppDelegate);
});

it('leaves the app delegate untouched when not enabled', () => {
expect(
updateAppDelegateLocationPermission(swiftAppDelegate, 'swift', false)
).toEqual(swiftAppDelegate);
});
});
6 changes: 6 additions & 0 deletions src/expo-plugins/@types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ export type IntercomRegion = 'US' | 'EU' | 'AU';
type BasePluginProps = {
/** Data hosting region for your Intercom workspace. Defaults to 'US' */
intercomRegion?: IntercomRegion;
/**
* iOS only. Registers a location permission provider so Mobile Carousel
* screens that ask for location permission are shown. Requires
* NSLocationWhenInUseUsageDescription in your Info.plist. Defaults to false.
*/
iosLocationPermission?: boolean;
};

type AutoInitPluginProps = BasePluginProps & {
Expand Down
2 changes: 2 additions & 0 deletions src/expo-plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
} from '@expo/config-plugins/build/ios/codeMod';
import type { IntercomPluginProps, IntercomRegion } from './@types';
import { withIntercomPushNotification } from './withPushNotifications';
import { withIosLocationPermission } from './withIosLocationPermission';

const mainApplication: ConfigPlugin<IntercomPluginProps> = (_config, props) =>
withMainApplication(_config, (config) => {
Expand Down Expand Up @@ -156,6 +157,7 @@ const infoPlist: ConfigPlugin<IntercomPluginProps> = (
const withIntercomIOS: ConfigPlugin<IntercomPluginProps> = (config, props) => {
let newConfig = appDelegate(config, props);
newConfig = infoPlist(newConfig, props);
newConfig = withIosLocationPermission(newConfig, props);
return newConfig;
};

Expand Down
147 changes: 147 additions & 0 deletions src/expo-plugins/withIosLocationPermission.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { type ConfigPlugin, withAppDelegate } from '@expo/config-plugins';
import {
mergeContents,
removeContents,
} from '@expo/config-plugins/build/utils/generateCode';
import {
insertContentsInsideObjcFunctionBlock,
insertContentsInsideSwiftFunctionBlock,
} from '@expo/config-plugins/build/ios/codeMod';
import type { IntercomPluginProps } from './@types';

const PROVIDER_TAG = 'Intercom location permission provider';

const SWIFT_PROVIDER = `import CoreLocation
import Intercom

final class IntercomLocationPermissionProvider: NSObject, ICMLocationPermissionProvider, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()

var authorizationStatusDidChange: ((ICMLocationAuthorizationStatus) -> Void)?

override init() {
super.init()
locationManager.delegate = self
}

func currentAuthorizationStatus() -> ICMLocationAuthorizationStatus {
ICMLocationAuthorizationStatus(rawValue: Int(locationManager.authorizationStatus.rawValue)) ?? .notDetermined
}

func requestWhenInUsePermission() {
locationManager.requestWhenInUseAuthorization()
}

func requestAlwaysPermission() {
locationManager.requestAlwaysAuthorization()
}

func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
authorizationStatusDidChange?(currentAuthorizationStatus())
}
}
`;

const OBJC_PROVIDER = `#import <CoreLocation/CoreLocation.h>
#import <Intercom/Intercom.h>

@interface IntercomLocationPermissionProvider : NSObject <ICMLocationPermissionProvider, CLLocationManagerDelegate>
@end

@implementation IntercomLocationPermissionProvider {
CLLocationManager *_locationManager;
}

@synthesize authorizationStatusDidChange = _authorizationStatusDidChange;

- (instancetype)init {
if ((self = [super init])) {
_locationManager = [CLLocationManager new];
_locationManager.delegate = self;
}
return self;
}

- (ICMLocationAuthorizationStatus)currentAuthorizationStatus {
return (ICMLocationAuthorizationStatus)_locationManager.authorizationStatus;
}

- (void)requestWhenInUsePermission {
[_locationManager requestWhenInUseAuthorization];
}

- (void)requestAlwaysPermission {
[_locationManager requestAlwaysAuthorization];
}

- (void)locationManagerDidChangeAuthorization:(CLLocationManager *)manager {
if (self.authorizationStatusDidChange) {
self.authorizationStatusDidChange([self currentAuthorizationStatus]);
}
}

@end
`;

const SWIFT_REGISTRATION =
'Intercom.setLocationPermissionProvider(IntercomLocationPermissionProvider())';
const OBJC_REGISTRATION =
'[Intercom setLocationPermissionProvider:[IntercomLocationPermissionProvider new]];';

export function updateAppDelegateLocationPermission(
contents: string,
language: string,
enabled: boolean
): string {
const isSwift = language === 'swift';
const registration = isSwift ? SWIFT_REGISTRATION : OBJC_REGISTRATION;

if (!enabled) {
return removeContents({ src: contents, tag: PROVIDER_TAG })
.contents.split('\n')
.filter((line) => !line.includes(registration))
.join('\n');
}

const src = mergeContents({
src: contents,
newSrc: isSwift ? SWIFT_PROVIDER : OBJC_PROVIDER,
tag: PROVIDER_TAG,
comment: '//',
anchor: isSwift
? /^(@UIApplicationMain|@main)\b/m
: /^@implementation AppDelegate\b/m,
offset: 0,
}).contents;

if (src.includes(registration)) {
return src;
}

return isSwift
? insertContentsInsideSwiftFunctionBlock(
src,
'application(_:didFinishLaunchingWithOptions:)',
registration,
{ position: 'tailBeforeLastReturn' }
)
: insertContentsInsideObjcFunctionBlock(
src,
'application didFinishLaunchingWithOptions:',
registration,
{ position: 'tailBeforeLastReturn' }
);
}

export const withIosLocationPermission: ConfigPlugin<IntercomPluginProps> = (
_config,
props
) =>
withAppDelegate(_config, (config) => {
config.modResults.contents = updateAppDelegateLocationPermission(
config.modResults.contents,
config.modResults.language,
props.iosLocationPermission === true
);
return config;
});