react-native-wifi-reborn

repository·master·Indexed 19 days ago

https://github.com/juansebestia/react-native-wifi-reborn

A React Native library for managing Wi-Fi connections on Android and iOS. It allows developers to connect to protected SSIDs, retrieve the current SSID, and manage network configurations. The library provides platform-specific functionality, including Wi-Fi scanning and hardware control for Android, and NEHotspotConfiguration methods for iOS. Version 4.13.6 supports autolinking for React Native 60+ and includes an Expo prebuild plugin.

Tokens
7.2K
Snippets
21
Records
26
Agent score
66%

What's inside react-native-wifi-reborn

  1. Configure Expo Prebuild Plugin

    master

    This package requires custom native code and cannot be used in the standard 'Expo Go' app. To use it with Expo, add the react-native-wifi-reborn plugin to your app.json or app.config.js:

    {
      "expo": {
        "ios": {
          "infoPlist": {
            "NSLocalNetworkUsageDescription": "The app requires access to the local network so it can..."
          }
        },
        "plugins": ["react-native-wifi-reborn"]
      }
    }

    Plugin Props:

    • fineLocationPermission (false | undefined): If set to false, android.permission.ACCESS_FINE_LOCATION will not be added to the AndroidManifest.xml.
    {
      "plugins": [
        [
          "react-native-wifi-reborn",
          {
            "fineLocationPermission": false
          }
        ]
      ]
    }
  2. Configure iOS requirements

    master

    To use react-native-wifi-reborn on iOS, you must complete the following steps:

    1. Permissions: Add NSLocalNetworkUsageDescription to your Info.plist to allow joining other networks.
    2. Capabilities: In Xcode, under your project settings, add the following capabilities via '+ Capability':
      • Access WIFI Information (required to access Wi-Fi information)
      • Hotspot Configuration (required to connect to networks)
    3. iOS 13+ Location Permissions: You must include either Privacy - Location When In Use Usage Description or Privacy - Location Always and When In Use Usage Description in your Info.plist settings.
  3. Configure Android for IoT device communication

    master

    If your app needs to connect to and send data to IoT devices, you must configure Android's network security to allow cleartext traffic for the device's IP.

    1. Create android/app/src/main/res/xml/network_security_config.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <domain-config cleartextTrafficPermitted="true">
            <domain includeSubdomains="true">IP_ADDRESS</domain>
        </domain-config>
    </network-security-config>

    Replace IP_ADDRESS with your device IP (e.g., 192.168.4.1).

    1. Update android/app/src/main/AndroidManifest.xml inside the <application> tag:
    <application
      ...
      android:networkSecurityConfig="@xml/network_security_config"
    >
    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <domain-config cleartextTrafficPermitted="true">
            <domain includeSubdomains="true">192.168.4.1</domain>
        </domain-config>
    </network-security-config>
  4. Force Wi-Fi usage for IoT commissioning on Android

    master

    When commissioning IoT devices that do not provide internet access, you can use forceWifiUsageWithOptions to route all app network requests through the Wi-Fi network instead of the mobile connection.

    Warning: You must disable this setting after use. Even if the app disconnects from the Wi-Fi network, it will continue to attempt routing all traffic through Wi-Fi if this is not turned off.

    Method

    forceWifiUsageWithOptions(useWifi: boolean, options: Record<string, unknown>): Promise<void>

    Options

    • noInternet: Boolean. Set to true to indicate the Wi-Fi network does not have internet connectivity.
    // Example: Routing traffic to an IoT device without internet
    await WifiManager.forceWifiUsageWithOptions(true, { noInternet: true });
    
    // IMPORTANT: Disable after use
    await WifiManager.forceWifiUsageWithOptions(false, {});
  5. Reload the application to see changes

    master

    After modifying code (e.g., in App.tsx), you can reload the app to apply changes without a full rebuild:

    • Android: Press the <kbd>R</kbd> key twice or open the Developer Menu (<kbd>Ctrl</kbd> + <kbd>M</kbd> on Windows/Linux, or <kbd>Cmd ⌘</kbd> + <kbd>M</kbd> on macOS) and select "Reload".
    • iOS: Press <kbd>Cmd ⌘</kbd> + <kbd>R</kbd> in the iOS Simulator.
  6. Run the example project

    master

    To run the provided example project, you must first ensure your React Native environment is set up. The process involves starting the Metro bundler and then launching the application on your target platform (Android or iOS).

    1. Start the Metro Server

    Run this from the root of the project to start the JavaScript bundler:

    npm start
    # OR
    yarn start

    2. Launch the Application

    Open a new terminal and run the command for your desired platform:

    For Android:

    npm run android
    # OR
    yarn android

    For iOS:

    npm run ios
    # OR
    yarn ios
    npm start
    npm run android
  7. Configure Android requirements

    master

    For Android 6 and above, you must request the ACCESS_FINE_LOCATION permission at runtime to enable Wi-Fi scanning and management. You can use PermissionsAndroid from react-native to handle this.

    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
    }
  8. Configure Metro for Expo Monorepos

    master

    When using react-native-wifi-reborn within an Expo monorepo structure, you must configure metro.config.js to ensure Metro can resolve dependencies from both the local project directory and the workspace root.

    To set this up:

    1. Set config.watchFolders to include the workspaceRoot so Metro monitors all files in the monorepo.
    2. Update config.resolver.nodeModulesPaths to include both the local node_modules and the workspaceRoot/node_modules.
    3. Set config.resolver.disableHierarchicalLookup to true to force Metro to resolve dependencies strictly from the specified nodeModulesPaths.
    const { getDefaultConfig } = require('expo/metro-config');
    const path = require('path');
    
    const projectRoot = __dirname;
    const workspaceRoot = path.resolve(projectRoot, '../..');
    
    const config = getDefaultConfig(projectRoot);
    
    // 1. Watch all files within the monorepo
    config.watchFolders = [workspaceRoot];
    
    // 2. Let Metro know where to resolve packages and in what order
    config.resolver.nodeModulesPaths = [
        path.resolve(projectRoot, 'node_modules'),
        path.resolve(workspaceRoot, 'node_modules'),
    ];
    
    // 3. Force Metro to resolve (sub)dependencies only from the `nodeModulesPaths`
    config.resolver.disableHierarchicalLookup = true;
    
    module.exports = config;
  9. Configure the Expo Config Plugin for react-native-wifi-reborn

    master

    To use react-native-wifi-reborn in an Expo project (using Prebuild), you can use the provided Config Plugin. This plugin automates the necessary permission settings for both iOS and Android.

    Supported Props

    PropTypeDefaultDescription
    fineLocationPermissionbooleantrueIf set to false, the plugin will NOT add android.permission.ACCESS_FINE_LOCATION to your AndroidManifest.xml.

    iOS Configuration

    The plugin automatically adds the following entitlements to your entitlements.plist:

    • com.apple.developer.networking.HotspotConfiguration
    • com.apple.developer.networking.wifi-info

    Android Configuration

    By default, the plugin adds android.permission.ACCESS_FINE_LOCATION to your AndroidManifest.xml. If you pass { fineLocationPermission: false } in the plugin props, this permission will be omitted.

    // Example usage in app.config.ts or app.json
    import { withWifi } from 'react-native-wifi-reborn/plugin';
    
    export default {
      expo: {
        plugins: [
          [withWifi, { fineLocationPermission: true }]
        ]
      }
    };
  10. Check and set Wi-Fi enabled status on Android

    master

    Use isEnabled() to check the current state of the device's Wi-Fi and setEnabled() to toggle it.

    Note: On Android 6+, these operations may require location permissions and for location services to be enabled.

    // Check if Wi-Fi is enabled
    const enabled = await WifiManager.isEnabled();
    this.setState({wifiIsEnabled: enabled});
    
    // Set Wi-Fi ON
    WifiManager.setEnabled(true);
    
    // Set Wi-Fi OFF
    WifiManager.setEnabled(false);
  11. Get current Wi-Fi SSID

    master

    Use getCurrentWifiSSID() to retrieve the SSID of the currently connected Wi-Fi network. This method returns a Promise.

    Errors:

    • couldNotDetectSSID: Occurs if the device is not connected or is in the process of connecting.
    import WifiManager from "react-native-wifi-reborn";
    
    try {
      const currentSSID = await WifiManager.getCurrentWifiSSID();
      console.log(`Your current Wi-Fi SSID is ${currentSSID}`);
    } catch (error) {
      console.log("Cannot get current SSID!");
    }