@abl-solutions/wifi-connect
v0.9.2
Published
The WiFi Connect React Native SDK enables the use of WiFi WPA2-Enterprise networks on mobile devices that are managed and operated by abl solutions GmbH
Downloads
210
Readme
WiFi Connect - React Native SDK
React Native SDK to configure and use WiFi networks managed and operated by abl solutions GmbH
- Requirements
- Release Note
- Installation
- Configure the WifiConnectService
- wifiConnectService API
- Configure the WifiCampaignService
- CampaignService API
- Error handling
- Limitations
Requirements
Android
Required permissions:
android.permission.INTERNET
android.permission.CHANGE_WIFI_STATE
android.permission.ACCESS_WIFI_STATE
Minimum required SDK version: 24 (Android 7 - Nougat)
iOS
Required entitlements (capabilities):
com.apple.developer.networking.HotspotConfiguration
(Hotspot Configuration)com.apple.developer.networking.wifi-info
(Access WiFi Information)
Minimum required iOS version: 11.0
Release Note
In this version of SDK 0.8.1 - push notifications permission is not required. If you want to use this - use 0.8.0.
For SDK v.0.8.0 User should grant Push notifications permission to be abl connect to Wifi via SDK (e.g. save config for auto-connect). Android <= 12 - not required - it's enabled by default.
Installation
Run
npm install @abl-solutions/wifi-connect
or
yarn add @abl-solutions/wifi-connect
For IOS:
cd ./ios && pod install
Android 13 and higher (For 0.8.0)
You should add this line to your app level manifest file and ask permission for push notifications.
<uses-permission android:id="android.permission.POST_NOTIFICATIONS"/>
Configure the WifiConnectService
initWifiConnectService Options:
| Property | required | Type | Description |
| -------------------------------------------------------------- | :------: | :-------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| accessToken | ✅ | string
| An access token that allows access to the WiFi Connect API for the current user. |
| ignoreNetworkErrorOnSimulator | | boolean
| Usually, network and WiFi support is limited running on a simulator. Therefore, the WiFi configuration can not be stored on a simulated device. In such a case WifiConnect.connectToWifi()
will reject with the error code E_NOT_SUPPORTED_ON_SIMULATOR
. If you don't want to reject with this error but instead resolve successfully, set this value to true
. Defaults to false
. |
| wifiApiEndpoint | | boolean
| Optionally set a different REST API endpoint that should be used by this library |
| isHiddenSSID | | boolean
| Specifies whether connection represents a hidden network. This value defaults to false if not specified. |
| android | | obejct
| Optional Android specific options. |
| android.timeSpanToWaitForPermissionDialogConfirmationInSeconds | | number
| This value is only used for connectToWifi
on Android 10 devices. This time span is used to wait for granting/declining the permission dialog which is shown by the Operating System. If the user declines the permission dialog within the time span, connectToWifi
will reject with the corresponding error code. If the user grants the permissions or the dialog is still opened, connectToWifi
will resolve after the time span. This value defaults to 10 seconds if not specified. |
import type { WifiConnectService } from '@abl-solutions/wifi-connect';
import { initWifiConnectService } from '@abl-solutions/wifi-connect';
const createWifiConnectService = (accessToken: string): WifiConnectService => {
return initWifiConnectService({
accessToken: accessToken,
android: {
timeSpanToWaitForPermissionDialogConfirmationInSeconds: 30,
},
ignoreNetworkErrorOnSimulator: true,
isHiddenSSID: true,
wifiApiEndpoint: 'https://api.wifi.connectivity.abl-solutions.io',
});
};
wifiConnectService = createWifiConnectService(auth.accessToken);
WifiConnectService API
connectToWifi(deviceId: string, user: User): Promise<void>;
Register this device to get direct access to abl's WiFi networks. The device will be configured to use this WiFi connection. This operation is an asynchrnous process and might take a few seconds to complete.
@param deviceId
A string that uniquely identifies this device.
@param user
Details about the user that owns the device.
@returns A void promise that resolves if the devices registration was successful and the WiFi configuration is stored in the device settings. Rejects if configuring the WiFi network failed for any reason. Rejects if push notifications permission not granted by user
.
Interfaces User
| Property | Type | Description |
| --------------- | :------: | :------------------------------------------------------------------ |
| email | string
| The e-mail address of the user. |
| preferredLocale | string
| The preferred locale that should be used to interact with the user. |
await wifiConnectService.connectToWifi(deviceId, {
email: email,
preferredLocale: preferredLocale,
});
getLatestLegalTerms(): Promise<LegalTerms>;
Gets the latest legal terms that must be accepted by the end-user to use the WiFi network. @returns A promise that resolves the legal terms or rejects if loading the legal terms failed.
Interfaces LegalTerms
| Property | Type | Description |
| ----------------------- | :------: | :--------------------------------------------------------------------- |
| legalTerms | string
| Legal terms content |
| version | string
| Version of legal terms |
| minimumVersion | string
| Minimum legal terms version which must be accepted to access the API. |
| dateMinLegalTermsActive | string
| The date at which the minimal version of legal terms will be enforced. |
const terms: LegalTerms = await wifiConnectService.getLatestLegalTerms();
legalTermsAccepted(): Promise<boolean>;
Checks whether the specified user already accepted the legal terms or not.
@returns true
if the user already accepted the legal terms, otherwise false.
const result: boolean = await wifiConnectService.legalTermsAccepted();
legalTermsAcceptedVersion(): Promise<string>
Checks the version of legal terms accepted by the user. @returns version of the legal terms that was accepted by the user. If the user didn't accepted any legal terms yet - returns 'undefined'
const result: string = await wifiConnectService.legalTermsAcceptedVersion();
acceptLegalTerms(legalTermsVersion: string): Promise<void>;
Accept the specified version of legal terms. This method needs to be called before a user
can register to connect to a WiFi network.
@param legalTermsVersion
The version of the legal terms.
await wifiConnectService.acceptLegalTerms(legalTermsVersion);
deleteWifiConfiguration(deviceId: string): Promise<void>;
Deletes the WiFi settings from the device and unregisters the device
from abl servers.
Basically, it just reverts the changes that were made by connectToWifi()
.
@param deviceId
A string that uniquely identifies this device.
await wifiConnectService.deleteWifiConfiguration(deviceId);
isWifiConfigured(): Promise<boolean>;
Check if the device is configured to connect to abl's WiFi network.
@returns true
if the device is configured; otherwise false
.
In case of error promise will reject with error.
try {
const result: boolean = await wifiConnectService.isWifiConfigured();
} catch (e) {
// Do something with an error
}
isConnectedToWifi(): Promise<boolean>;
(iOS only)
Check if device is connected to abl's WiFi network.
Method should be invoked after connectToWifi() to check connection by received SSID, othervise resolves with false
.
@returns true
if the device is connected; otherwise false
. This function works only on iOS devices.
import { Platform } from 'react-native';
if (Platform.OS === 'ios') {
setTimeout(async () => {
const result: boolean = await wifiConnectService.isConnectedToWifi();
}, 4000);
}
registerOnPermissionRejectedListener(callback: () => void): void;
Registers a callback that will be invoked if the required permissions are
revoked after connectToWifi
fullfilled. This callback can be used to handle
the case if a user rejects the permission dialog after the confirmation time span.
This callback should be unregistered (using unregisterOnPermissionRejectedListener
)
after usage to free internal resources.
This callback will only be invoked on Android 10 devices.
@param callback
The callback to invoke.
import { Alert } from 'react-native';
wifiConnectService.registerOnPermissionRejectedListener(() => {
Alert.alert('Permission rejected', 'Please accept...');
});
unregisterOnPermissionRejectedListener(): void;
Unregister the callback that was previously registered using registerOnPermissionRejectedListener
// return a clean up function to unregister the listener
return () => wifiConnectService?.unregisterOnPermissionRejectedListener();
Configure the WifiCampaignService
initCampaignService Options
| Property | required | Type | Description |
| ------------------- | :------: | :------: | :-------------------------------------------------------------------------------- |
| accessToken | ✅ | string
| An access token that allows access to the Campaign API for the current user. |
| campaignApiEndpoint | | string
| Optionally set a different REST API endpoint that should be used by this library. |
import type { CampaignService } from '@abl-solutions/wifi-connect';
import { initCampaignService } from '@abl-solutions/wifi-connect';
const createWifiCampaignService = (accessToken: string): CampaignService => {
return initCampaignService({
accessToken: accessToken,
campaignApiEndpoint: process.env.CAMPAIGN_API_ENDPOINT,
});
};
campaignService = createWifiCampaignService(auth.accessToken);
CampaignService API
getNextCampaign(deviceId: string): Promise<Campaign>;
Campaign
| Property | Type | Description |
| ------------ | :------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| campaignUrl | string
| A promise that resolves to a Campaign object if the campaign was fetched successfully. Rejects if fetching the next campaign failed for any reason. The Campaign object contains a flag Campaign.required that will be true if the user needs to watch a campaign. This will be the case if the timespan since watching the last campaign is greater than the configured timespan. If Campaign.required is false then it is not necessary to watch a campaign. |
| required | boolean
| This flag indicating if watching campaign required or not to prolong an access to wifi. |
| notification | Notification
| That's an object that contain title
and body
that could be string or null |
const campaign = await campaignService.getNextCampaign(deviceId);
shouldCloseCampaignView(campaignUrl: string): boolean;
Checking when to close campaign view - campaign at this step considered as watched.
const onNavigationStateChange = (navigationState: { url: string }) => {
if (campaignService.shouldCloseCampaignView(navigationState?.url)) {
setCampaign(undefined);
console.log('campaign viewed - closing webview');
}
};
Error handling
WifiConnect.connectToWifi(...)
and WifiConnect.deleteWifiConfiguration()
will reject if
configuring the wifi failed for any reason. The error object contains at least the following
properties:
{
"code": "string",
"message": "string"
}
Additionally, there can be any other properties depending on the error type and platform.
The error code specifies the type of error. The message provides an additional description of the error. Some of these error codes are only specific for a platform.
| Error Code | Description | Android | iOS |
| :---------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------ | :------------------------------------------------- |
| E_ACTIVITY_DOES_NOT_EXIST
| Will be thrown if the React Native context does not include a reference to the current activity. | yes | no |
| E_INVALID_WIFI_CONFIGURATION
| Will be thrown if the WiFi configuration is invalid. This might be a invalid username, password or certificate. If this error occours, this should be reported to abl. | yes | yes |
| E_USER_REJECTED
| The user rejected to connect to the WiFi network. | yes | yes |
| E_PERMISSION_DENIED
| The app is not authorized to configure WiFi networks on the device. | yes | no (iOS will throw E_UNKNOWN_ERROR
in this case) |
| E_FAILED_TO_ENABLE_NETWORK
| Android devices can store network configurations that are disabled. This error occours if enabling the network failed. Usually, this should not happen. | yes | no |
| E_RUNNING_ON_SIMULATOR
| Connecting to a WiFi network on simulator is not supported. If you want to ignore this error and get a successful response anyway, set WifiConnectOptions.ignoreNetworkErrorOnSimulator
to true
. | yes | yes |
| E_API_ERROR_UNAUTHORIZED
| The request failed because the provided access token is invalid, expired or a required scope is missing. | yes | yes |
| E_API_ERROR_BAD_REQUEST
| The request failed because one or more input arguments are missing or invalid. | yes | yes |
| E_API_ERROR_INTERNAL_SERVER_ERROR
| The request failed due to an error on abl servers. | yes | yes |
| E_API_ERROR
| The request failed for any unknown/unexpected reason. | yes | yes |
| E_UNKNOWN_ERROR
| Any other error case that is not described above. | yes | yes |
The library provides an enum with all possible error codes.
import { ErrorCode } from '@abl-solutions/wifi-connect';
In all cases where the error message starts with E_API_
, the thrown error contains an additional
property apiError
. This property contains additional information about the error. apiError
can
be of type string
or an object
that is JSON serializable.
Limitations
Android
The SDK has the following limitations on Android devices:
- Android 10 and later: If the user rejects the user approval dialog shown by the OS, the permission must be granted manually by the user from the device settings. See Android Developers - Wi-Fi infrastructure - Changing approval status for app. Also see Android Issue Tracker.
- Android 10 only: The user prompt to accept the WiFi configuration will only be visible in the "Android Quick Settings" menu.
- Android 9 and before: No user prompt to accept the WiFi configuration will be shown at all.
Running on Simulator
Simulators do not provide any possibility to simulate a real WiFi connection, because the real WiFi
adapter of the host machine can not be used. Therefore, it is not possible to use
WifiConnect.connectToWifi()
and WifiConnect.deleteWifiConfiguration()
in a simulator. Calling this
function will raise a E_RUNNING_ON_SIMULATOR
error. To overcome this issue in simulators, you can
set WifiConnectOptions.ignoreNetworkErrorOnSimulator
to true
in the init()
function. With this
option, configuring the WiFi connection will be skipped. But in any case the device will be registered
on abl servers. This is handy for testing other features like accepting legal terms or watching
campaigns.