To ensure that your React Native app has the necessary Local Network permissions on iOS before running the scanWifiNetworks API, you'll need to follow these steps:
- Update
Info.plist with Required Permissions
- Use a Permissions Library (e.g.,
react-native-permissions)
- Modify Your API Call to Check and Request Permissions
- Handle the Permission Prompt and User Response
Below is a comprehensive guide to implementing these steps:
1. Update Info.plist with Required Permissions
iOS requires you to declare the permissions your app needs in the Info.plist file. For Local Network access, add the following keys:
<key>NSLocalNetworkUsageDescription</key>
<string>Your description why the app needs access to the local network.</string>
<key>NSBonjourServices</key>
<array>
<string>_http._tcp</string>
<!-- Add other Bonjour services if needed -->
</array>
Steps to Update Info.plist:
- Open your project in Xcode.
- Navigate to the
Info.plist file.
- Add the keys mentioned above with appropriate descriptions.
2. Install and Configure react-native-permissions
We'll use the react-native-permissions library to handle permission checks and requests.
Install the Library:
yarn add react-native-permissions
# or
npm install react-native-permissions --save
Link the Library (if using React Native < 0.60):
react-native link react-native-permissions
For iOS, ensure you have the necessary configurations:
- Open your project in Xcode.
- Go to Capabilities and ensure that Local Network is enabled.
3. Modify Your API Call to Check and Request Permissions
We'll create a function to check the Local Network permission and request it if not already granted. Then, we'll integrate this check into your existing runScanApi function.
Import Necessary Modules:
import { Platform, Alert as RNAlert } from 'react-native';
import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions';
Create a Function to Check and Request Local Network Permission:
const checkLocalNetworkPermission = async () => {
if (Platform.OS !== 'ios') return true; // Permissions handled differently on Android
const permission = PERMISSIONS.IOS.LOCAL_NETWORK;
try {
let result = await check(permission);
switch (result) {
case RESULTS.UNAVAILABLE:
RNAlert.alert('Error', 'Local Network permission is not available on this device.');
return false;
case RESULTS.DENIED:
// Request permission
result = await request(permission);
return result === RESULTS.GRANTED;
case RESULTS.LIMITED:
// iOS 14: Limited access
return true;
case RESULTS.GRANTED:
// Permission granted
return true;
case RESULTS.BLOCKED:
// Permission blocked, prompt user to enable it in settings
RNAlert.alert(
'Permission Required',
'Local Network permission is blocked. Please enable it in Settings.',
[
{ text: 'Cancel', style: 'cancel' },
{ text: 'Open Settings', onPress: () => Linking.openSettings() },
]
);
return false;
default:
return false;
}
} catch (error) {
console.error('Permission check error:', error);
return false;
}
};
Modify the runScanApi Function:
const runScanApi = async () => {
const hasPermission = await checkLocalNetworkPermission();
if (!hasPermission) {
// Permission not granted, exit the function
return;
}
showLoader(true);
try {
const result = await althermaService.scanWifiNetworks();
if ('error' in result && result.error) {
setApiResponse(`Error: ${JSON.stringify(result.error)}`);
} else {
setApiResponse(`Success: ${JSON.stringify(result.data)}`);
}
} catch (error: any) {
setApiResponse(`Exception: ${error.message}`);
} finally {
showLoader(false);
}
};
4. Update Your UI to Handle Permission Prompts (Optional)
Depending on your app's UX design, you might want to notify users why the permission is needed before requesting it. You can use modals or pre-request screens to explain the necessity of Local Network access.
Full Updated Code Example
Here’s how your component might look after incorporating the permission check:
import React, { useState } from 'react';
import {
View,
Text,
ScrollView,
Platform,
Alert as RNAlert,
Linking
} from 'react-native';
import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions';
import Background from './Background'; // Assuming you have these components
import Alert from './Alert';
import Label from './Label';
import Button from './Button';
import styles from './styles'; // Your stylesheet
const YourComponent = ({ navigation }) => {
const [alertStatus, setAlertStatus] = useState({
isVisible: false,
title: '',
message: '',
positiveBtnLabel: '',
negativeBtnLabel: '',
alternativeBtnLabel: '',
buttonAlignment: 'center',
onPress: null,
onCancel: null,
onPressAlternate: null,
});
const [apiResponse, setApiResponse] = useState('');
const showLoader = (visible) => {
// Implement your loader logic here
};
const onDismissAlert = () => {
setAlertStatus({ ...alertStatus, isVisible: false });
};
const checkLocalNetworkPermission = async () => {
if (Platform.OS !== 'ios') return true;
const permission = PERMISSIONS.IOS.LOCAL_NETWORK;
try {
let result = await check(permission);
switch (result) {
case RESULTS.UNAVAILABLE:
RNAlert.alert('Error', 'Local Network permission is not available on this device.');
return false;
case RESULTS.DENIED:
result = await request(permission);
return result === RESULTS.GRANTED;
case RESULTS.LIMITED:
return true;
case RESULTS.GRANTED:
return true;
case RESULTS.BLOCKED:
RNAlert.alert(
'Permission Required',
'Local Network permission is blocked. Please enable it in Settings.',
[
{ text: 'Cancel', style: 'cancel' },
{ text: 'Open Settings', onPress: () => Linking.openSettings() },
]
);
return false;
default:
return false;
}
} catch (error) {
console.error('Permission check error:', error);
return false;
}
};
const runScanApi = async () => {
const hasPermission = await checkLocalNetworkPermission();
if (!hasPermission) {
return;
}
showLoader(true);
try {
const result = await althermaService.scanWifiNetworks();
if ('error' in result && result.error) {
setApiResponse(`Error: ${JSON.stringify(result.error)}`);
} else {
setApiResponse(`Success: ${JSON.stringify(result.data)}`);
}
} catch (error: any) {
setApiResponse(`Exception: ${error.message}`);
} finally {
showLoader(false);
}
};
// Similarly, modify other API functions if they require permissions
return (
<Background style={styles.root}>
<View style={styles.container}>
{/* <DaikinLiteWifiAlert
ssidPrefix={ALTHERMA_SSID}
navigation={navigation}
/> */}
<Alert
visible={alertStatus.isVisible}
title={alertStatus.title}
buttonAlignment={alertStatus.buttonAlignment}
description={alertStatus.message}
positiveButtonTitle={
alertStatus.positiveBtnLabel ||
translate(translationKeys.alert.okayButtonLabel)
}
negativeButtonTitle={alertStatus.negativeBtnLabel}
alternateButtonTitle={alertStatus.alternativeBtnLabel}
onPress={alertStatus.onPress || onDismissAlert}
onCancel={alertStatus.onCancel || onDismissAlert}
onPressAlternate={alertStatus.onPressAlternate || onDismissAlert}
/>
<Label
text="Click on the buttons below to check the Altherma APIs"
style={styles.description}
/>
<Button
title="Run Scan API"
style={[styles.scanButton]}
onPress={runScanApi}
/>
<Button
title="Run Networks API"
style={[styles.scanButton]}
onPress={runNetworksApi}
/>
<Button
title="Run Settings API"
style={[styles.scanButton]}
onPress={runSettingsApi}
/>
<Button
title="Run Info API"
style={[styles.scanButton]}
onPress={runInfoApi}
/>
<View style={styles.responseWrapper}>
<ScrollView
style={styles.responseContainer}
contentContainerStyle={{ flexGrow: 1 }}
>
<Text style={styles.responseText}>
{apiResponse || 'API response will appear here'}
</Text>
</ScrollView>
</View>
</View>
</Background>
);
};
export default YourComponent;
Additional Considerations
-
Handle Different Platforms: The permission check is specific to iOS. On Android, Local Network permissions are handled differently, and as of now, Android doesn't require a similar permission for local network access in the same way.
-
Testing on Real Devices: Some permissions, especially Local Network access, can behave differently on simulators/emulators. Always test on real devices to ensure proper functionality.
-
User Experience: Clearly explain to users why your app requires Local Network access to improve the likelihood of them granting the permission.
-
Error Handling: Ensure that all possible permission states are handled gracefully to prevent your app from crashing or behaving unexpectedly.
References
By following these steps, your app will check for Local Network permissions on iOS and prompt the user to grant access if necessary before attempting to run the scanWifiNetworks API.