react-native-wifi-reborn
v4.13.0
Published
A react-native implementation for viewing and connecting to Wifi networks on Android and iOS devices.
Downloads
35,617
Maintainers
Readme
react-native-wifi-reborn
This project is based on the no longer maintained https://github.com/robwalkerco/react-native-wifi.
Getting started
$ npm install react-native-wifi-reborn
iOS
You need use enable Access WIFI Information
, with correct profile. Hotspot Configuration
is required in order to connect to networks.
iOS 13
You need put "Privacy - Location When In Use Usage Description" or "Privacy - Location Always and When In Use Usage Description" in Settings -> info
Android
ACCESS_FINE_LOCATION
permission
Since Android 6, you must request the ACCESS_FINE_LOCATION
permission at runtime to use the device's Wi-Fi scanning and managing capabilities. In order to accomplish this, you can use the PermissionsAndroid API or React Native Permissions.
Example:
import { PermissionsAndroid } from 'react-native';
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location permission is required for WiFi connections',
message:
'This app needs location permission as this is required ' +
'to scan for wifi networks.',
buttonNegative: 'DENY',
buttonPositive: 'ALLOW',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
// You can now use react-native-wifi-reborn
} else {
// Permission denied
}
Autolinking (React Native 60+)
This library is correctly autolinked on React Native 60+ 🎉.
React Native Link (for React Native 0.59 and below)
$ react-native link react-native-wifi-reborn
Manual linking
iOS
- In XCode, in the project navigator, right click
Libraries
➜Add Files to [your project's name]
- Go to
node_modules
➜react-native-wifi-reborn
and addRNWifi.xcodeproj
- In XCode, in the project navigator, select your project. Add
libRNWifi.a
to your project'sBuild Phases
➜Link Binary With Libraries
- Run your project (
Cmd+R
)<
Android
- Open up
android/app/src/main/java/[...]/MainActivity.java
- Add
import com.reactlibrary.rnwifi.RNWifiPackage;
to the imports at the top of the file - Add
new RNWifiPackage()
to the list returned by thegetPackages()
method
- Append the following lines to
android/settings.gradle
:include ':react-native-wifi-reborn' project(':react-native-wifi-reborn').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-wifi-reborn/android')
- Insert the following lines inside the dependencies block in
android/app/build.gradle
:implementation project(':react-native-wifi-reborn')
Prebuild Plugin
This package cannot be used in the "Expo Go" app because it requires custom native code.
After installing this npm package, add the config plugin to the plugins
array of your app.json
or app.config.js
:
{
"expo": {
"plugins": ["react-native-wifi-reborn"]
}
}
Next, rebuild your app as described in the "Adding custom native code" guide.
Props
The plugin provides props for extra customization. Every time you change the props or plugins, you'll need to rebuild (and prebuild
) the native app. If no extra properties are added, defaults will be used.
fineLocationPermission
(false | undefined): Whenfalse
, theandroid.permission.ACCESS_FINE_LOCATION
will not be added to theAndroidManifest.xml
.
Example
{
"plugins": [
[
"react-native-wifi-reborn",
{
"fineLocationPermission": false
}
]
]
}
Usage
import WifiManager from "react-native-wifi-reborn";
WifiManager.connectToProtectedWifiSSID(ssid, password, isWep).then(
() => {
console.log("Connected successfully!");
},
() => {
console.log("Connection failed!");
}
);
WifiManager.getCurrentWifiSSID().then(
ssid => {
console.log("Your current connected wifi SSID is " + ssid);
},
() => {
console.log("Cannot get current SSID!");
}
);
Methods
The api documentation is in progress.
Android & iOS
The following methods work on both Android and iOS
connectToProtectedSSID(SSID: string, password: string, isWEP: boolean, isHidden: boolean, timeout: number): Promise
Returns a promise that resolves when connected or rejects with the error when it couldn't connect to the wifi network.
SSID
Type: string
The SSID of the wifi network to connect with.
password
Type: string
The password of the wifi network to connect with.
isWep
Type: boolean
Used on iOS. If true, the network is WEP Wi-Fi; otherwise it is a WPA or WPA2 personal Wi-Fi network.
isHidden
Type: boolean
Used on Android. If true, the network is a hidden Wi-Fi network.
timeout - ONLY NEW VERSION
Type: number
Used on Android to set a timeout in seconds. Default 15 seconds.
Errors:
- iOS:
unavailableForOSVersion
: Starting from iOS 11, NEHotspotConfigurationError is available.invalid
: If an unknown error is occurred.invalidSSID
: If the SSID is invalid.invalidSSIDPrefix
: If the SSID prefix is invalid.invalidPassphrase
: If the passphrase is invalid.userDenied
: If the user canceled the request to join the asked network.locationPermissionDenied
: Starting from iOS 13, location permission is denied.locationPermissionRestricted
: Starting from iOS 13, location permission is restricted.couldNotDetectSSID
: If the SSID couldn't be detected.
- Android:
locationPermissionMissing
: Starting android 6, location permission needs to be granted for wifi scanning.locationServicesOff
: Starting Android 6, location services needs to be on to scan for wifi networks.couldNotEnableWifi
: Starting Android 10, apps are no longer allowed to enable wifi. User has to manually do this.couldNotScan
: Starting Android 9, it's only allowed to scan 4 times per 2 minuts in a foreground app.didNotFindNetwork
: If the wifi network is not in range, the security type is unknown and WifiUtils doesn't support connecting to the network.authenticationErrorOccurred
: Authentication error occurred while trying to connect. The password could be incorrect or the user could have a saved network configuration with a different password!android10ImmediatelyDroppedConnection
: Firmware bugs on OnePlus prevent it from connecting on some firmware versions. More info: https://github.com/ThanosFisherman/WifiUtils/issues/63.timeoutOccurred
: Could not connect in the timeout window. -ONLY NEW VERSION
- Both:
unableToConnect
: When an unknown error occurred.
getCurrentWifiSSID(): Promise
Returns the SSID of the current WiFi network.
Errors:
couldNotDetectSSID
: Not connected or connecting.
Only iOS
The following methods work only on iOS
connectToSSID(ssid: string): Promise
connectToSSIDPrefix(ssid: string): Promise
disconnectFromSSID(ssid: string): Promise
connectToProtectedSSIDOnce(SSID: string, password: string, isWEP: boolean, joinOnce: boolean): Promise
connectToProtectedSSIDPrefix(SSIDPrefix: string, password: string, isWep: boolean): Promise
connectToProtectedSSIDPrefixOnce(SSIDPrefix: string, password: string, isWep: boolean, joinOnce: boolean): Promise
Use this function when you want to match a known SSID prefix, but don’t have a full SSID. If the system finds multiple Wi-Fi networks whose SSID string matches the given prefix, it selects the network with the greatest signal strength.
SSIDPrefix
Type: string
A prefix string to match the SSID of a Wi-Fi network.
password
Type: string
The password of the wifi network to connect with.
isWep
Type: boolean
Used on iOS. If YES, the network is WEP Wi-Fi; otherwise it is a WPA or WPA2 personal Wi-Fi network.
joinOnce
Type: boolean
Used on iOS. Optional param. Defaults to false
. When joinOnce is set to true, the hotspot remains configured and connected only as long as the app that configured it is running in the foreground. The hotspot is disconnected and its configuration is removed when any of the following events occurs:
The app stays in the background for more than 15 seconds.
The device sleeps.
The app crashes, quits, or is uninstalled.
The app connects the device to a different Wi-Fi network.
The user connects the device to a different Wi-Fi network.
Errors:
unavailableForOSVersion
: Starting from iOS 11, NEHotspotConfigurationError is available.invalid
: If an unknown error is occurred.invalidSSID
: If the SSID is invalid.invalidSSIDPrefix
: If the SSID prefix is invalid.invalidPassphrase
: If the passphrase is invalid.userDenied
: If the user canceled the request to join the asked network.locationPermissionDenied
: Starting from iOS 13, location permission is denied.locationPermissionRestricted
: Starting from iOS 13, location permission is restricted.couldNotDetectSSID
: If the SSID couldn't be detected.unableToConnect
: When an unknown error occurred.
Only Android
The following methods work only on Android
loadWifiList(): Promise<Array<WifiEntry>>
Returns a list of nearby WiFI networks.
SSID
: The network name.BSSID
: The WiFi BSSID.capabilities
: Describes the authentication, key management, and encryption schemes supported by the access point.frequency
: The primary 20 MHz frequency (in MHz) of the channel over which the client is communicating with the access point.level
: The detected signal level in dBm, also known as the RSSI.timestamp
: timestamp in microseconds (since boot) when this result was last seen.
Errors:
locationPermissionMissing
: Starting android 6, location permission needs to be granted for wifilocationServicesOff
: Starting Android 6, location services needs to be on to scan for wifi networks.exception
: Any other caught exception.
reScanAndLoadWifiList(): Promise<Array<WifiEntry>>
Similar to loadWifiList
but it forcefully starts a new WiFi scan and only passes the results when the scan is done.
isEnabled(): Promise<boolean>
Method to check if WiFi is enabled.
const enabled = await WifiManager.isEnabled();
this.setState({wifiIsEnabled: enabled});
setEnabled(enabled: boolean)
Method to set the WiFi on or off on the user's device.
WifiManager.setEnabled(true); //set WiFi ON
WifiManager.setEnabled(false); //set WiFi OFF
connectionStatus(): Promise<boolean>
Returns if the device is currently connected to a WiFi network.
disconnect()
Disconnect currently connected WiFi network.
getBSSID(): Promise<string>
Returns the BSSID (basic service set identifier) of the currently connected WiFi network.
getCurrentSignalStrength(): Promise<number>
Returns the RSSI (received signal strength indicator) of the currently connected WiFi network.
getFrequency(): Promise<number>
Returns the frequency of the currently connected WiFi network.
getIP(): Promise<number>
Returns the IP of the currently connected WiFi network.
isRemoveWifiNetwork(ssid: String): Promise<boolean>
This method will remove the wifi network configuration. If you are connected to that network, it will disconnect.
Errors:
locationPermissionMissing
: Starting android 6, location permission needs to be granted for wifi
forceWifiUsage(useWifi: boolean): Promise<void>
Deprecated; see forceWifiUsageWithOptions.
forceWifiUsageWithOptions(useWifi: boolean, options<Record<string, unknown>): Promise<void>
Use this to execute api calls to a wifi network that does not have internet access. Useful for commissioning IoT devices. This will route all app network requests to the network (instead of the mobile connection). It is important to disable it again after using as even when the app disconnects from the wifi network it will keep on routing everything to wifi.
options
noInternet: Boolean
: Indicate the wifi network does not have internet connectivity.
Conventions
- Anuglar JS Git Commit conventions are used, read more: https://gist.github.com/stephenparish/9941e89d80e2bc58a153#recognizing-unimportant-commits