android - 如何在 iOS 和 Android 的 React Native 应用程序中检查互联网连接?
问题描述
我有一个 React Native 应用程序,我正在寻求添加功能,以检查应用程序首次启动时是否存在活动的 Internet 连接,并在此后不断地检查。
如果没有互联网连接,我正在寻求显示一条消息“未检测到互联网连接”,并带有“重试”按钮;如果有互联网连接,我正在寻求加载页面(WebView)。
我也在寻求同时支持 iOS 和 Android 设备;我对此进行了独立研究,并在 GitHub 上找到了几个库。但是,许多需要在 Android Manifest XML 中添加权限的额外步骤,但是我在我的应用程序中看不到 Android Manifest XML 文件;为什么只有 Android 需要清单?
任何帮助表示赞赏;谢谢并保重。
解决方案
请阅读此https://reactnativeforyou.com/how-to-check-internet-connectivity-in-react-native-android-and-ios/链接。
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>
);
}
}
推荐阅读
- php - 灯泡服务器中的碳投掷错误
- swift4.1 - URLSession.shared.dataTask 在没有 .resume() 的情况下无法工作
- angular - 在科尔多瓦离子本机应用程序中为openID连接指定重定向uri的位置
- c# - 如何在 FluentValidation 的世界中使用带有 ValidateAsync 的规则集?
- python - 过滤满足一组标准的多对多关系
- asp.net - 可以将纯文本密码发送到服务器端进行身份验证吗?避免这种纯文本传输的常用方法是什么
- symfony - Symfony 4 - Lexik/JwtAuthenticationBundle - 无法更改 token_ttl 默认值
- html - 如何在输入中进行 Html 电子邮件验证?
- flutter - 禁用 DropdownButton 会导致布局错误
- javascript - 无法将 Observable 转换为 Object[]