问题描述
我有一个 React Native 应用程序,我正在寻求添加功能,以在应用程序首次启动时检查是否有活动的互联网连接,并在此后不断检查.
I have a React Native application and I'm seeking to add functionality that checks if there is an active internet connection when the app first starts up, and continuously thereafter.
如果没有互联网连接,我试图显示一条消息未检测到互联网连接",并带有一个再试一次"按钮;如果有互联网连接,我正在尝试加载一个页面 (WebView).
If there is no internet connection, I'm seeking to display a message saying "Internet connection not detected" with a button to "Try again"; if there is an internet connection, I'm seeking to load a page (WebView).
我也在寻求同时支持 iOS 和 Android 设备;我已经独立研究过这个,并在 GitHub 上找到了几个库.但是,许多需要在 Android Manifest XML 中添加权限的额外步骤,但是我在我的应用程序中没有看到 Android Manifest XML 文件;为什么只有 Android 需要清单?
I'm also seeking to support both iOS and Android devices; I've researched this independently and have found a couple libraries on GitHub. However, many require an extra step of including a permissions addition in Android Manifest XML, however I don't see an Android Manifest XML file in my app; why does only Android need a manifest?
感谢任何帮助;谢谢并保重.
Any help is appreciated; thanks and take care.
推荐答案
请阅读此https://reactnativeforyou.com/how-to-check-internet-connectivity-in-react-native-android-and-ios/ 链接.>
Please read this https://reactnativeforyou.com/how-to-check-internet-connectivity-in-react-native-android-and-ios/ link.
import React, { Component } from "react";
import { View, Text, Button, Alert, NetInfo, Platform } from "react-native";
export default class componentName extends Component {
constructor(props) {
super(props);
this.state = {};
}
CheckConnectivity = () => {
// For Android devices
if (Platform.OS === "android") {
NetInfo.isConnected.fetch().then(isConnected => {
if (isConnected) {
Alert.alert("You are online!");
} else {
Alert.alert("You are offline!");
}
});
} else {
// For iOS devices
NetInfo.isConnected.addEventListener(
"connectionChange",
this.handleFirstConnectivityChange
);
}
};
handleFirstConnectivityChange = isConnected => {
NetInfo.isConnected.removeEventListener(
"connectionChange",
this.handleFirstConnectivityChange
);
if (isConnected === false) {
Alert.alert("You are offline!");
} else {
Alert.alert("You are online!");
}
};
render() {
return (
<View>
<Button
onPress={() => this.CheckConnectivity()}
title="Check Internet Connectivity"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
</View>
);
}
}
这篇关于如何在 iOS 和 Android 的 React Native 应用程序中检查互联网连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!