This content originally appeared on DEV Community and was authored by RamR
Establish WiFi connection in a React native application.
Packages
- react-native-permissions config
- @react-native-community/geolocation config
- react-native-wifi-reborn config
- @react-native-tethering/wifi config
Note, we need location permission to connect wifi.
Front Page
import React, { useState } from 'react';
import {
View,
Text,
StyleSheet,
PermissionsAndroid,
Platform,
} from 'react-native';
import { TextInput, Button } from 'react-native-paper';
export default function App() {
const [ssid, setSsid] = useState('');
const [password, setPassword] = useState('');
return (
<View style={styles.container}>
<Text style={styles.text}>Connect to Network</Text>
<TextInput
style={styles.input}
label="SSID"
value={ssid}
onChangeText={(text) => setSsid(text)}
/>
<TextInput
style={styles.input}
label="Password"
value={password}
onChangeText={(text) => setPassword(text)}
/>
<Button
icon="wifi"
mode="contained"
style={{ marginTop: 20 }}
onPress={() => ()}>
Connect
</Button>
</View>
);
}
Turn on Location
import { request, PERMISSIONS, RESULTS } from 'react-native-permissions';
import Geolocation from '@react-native-community/geolocation';
const isAndroid = Platform.OS === 'android';
export default function App() {
. . .
const requestLocationPermission = async () => {
var given = false;
if (isAndroid) {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Permission',
message:
'This app needs access to your location to manage wifi networks',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('GRANTED Location permission granted');
given = true;
} else {
console.log('Location permission denied');
}
} catch (err) {
console.warn(err);
}
} else {
const result = await request(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE);
if (result === RESULTS.GRANTED) {
console.log('IOS GRANTED Location permission granted');
given = true;
} else {
Alert.alert('Location permission denied');
}
}
return given;
};
const turnOnLocation = async () => {
var permit = await requestLocationPermission();
if (!permit) return false;
var result = await new Promise((resolve, reject) => {
Geolocation.getCurrentPosition(
(position) => {
console.log(position);
resolve(true);
},
(error) => {
console.log(error.code, error.message);
resolve(false);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
});
console.log('turnOnLocation result', result);
return result;
};
. . .
Connect WiFi
Based on my experience, I figured out TetheringManager will do the job for android and WifiManager for iOS.
But while using TetheringManager the iOS app getting crashed. So I'm going to have 2 different files separately for android and iOS.
Let's rename the file as wificonnect.android.js and duplicate this file as wificonnect.ios.js.
wificonnect.android.js
import TetheringManager from "@react-native-tethering/wifi";
export default function App() {
. . .
const requestLocationPermission = async () => {. . .};
const turnOnLocation = async () => {. . .};
const connectWifi = async () => {
try {
const granted = await turnOnLocation();
if (granted) {
const wifiEnabled = await TetheringManager.isWifiEnabled();
if (!wifiEnabled) {
await TetheringManager.setWifiEnabled();
connectWifi();
return;
}
await TetheringManager.connectToNetwork({
ssid: ssid,
password: password,
isHidden: true,
})
.then(
() => {
console.log("wifi Connected successfully!");
alert(" wifi network connected.");
},
(error) => {
console.log("Connection failed! ", error);
alert("unable to connect wifi\n\n" + error);
}
)
.catch((err) => {
console.log("Connection failed! ", err);
alert("unable to connect wifi\n\n" + err);
});
} else {
console.log(
"unable to connect wifi\n\n" +
"Location service is turned off or Location permission denied"
);
alert(
"unable to connect wifi\n\n" +
"Location service is turned off or Location permission denied"
);
}
} catch (err1) {
alert("unable to connect wifi\n\n" + err1);
}
};
return (
. . .
<Button
icon="wifi"
mode="contained"
style={{ marginTop: 20 }}
onPress={() => connectWifi()}
>
Connect
</Button>
. . .
);
}
wificonnect.ios.js
import WifiManager from "react-native-wifi-reborn";
. . .
const connectWifi = async () => {
try {
const granted = await turnOnLocation();
if (granted) {
/**
WifiManager.connectToProtectedSSID(ssid, password, try with both 'true' and 'false')
*/
WifiManager.connectToProtectedSSID(ssid, password, true)
.then(
() => {
console.log("wifi Connected successfully!");
alert("wifi network connected.");
},
(error) => {
console.log("Connection failed! ", error);
alert("unable to connect wifi\n\n" + error);
}
)
.catch((err) => {
console.log("Connection failed! ", err);
alert("unable to connect wifi\n\n" + err);
});
} else {
console.log(
"unable to connect wifi\n\n" +
"Location service is turned off or Location permission denied"
);
alert(
"unable to connect wifi\n\n" +
"Location service is turned off or Location permission denied"
);
}
} catch (err1) {
alert("unable to connect wifi\n\n" + err1);
}
};
App.js
import WifiConnect from "./wificonnect"
export default function App() {
return <WifiConnect />;
}
Full code here
Thank You.
This content originally appeared on DEV Community and was authored by RamR
RamR | Sciencx (2024-09-20T11:29:46+00:00) React Native WiFi Connect. Retrieved from https://www.scien.cx/2024/09/20/react-native-wifi-connect/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.