@react-native-community/netinfo
提供对网络信息的访问的跨平台 API。
@react-native-community/netinfo 允许你获取关于连接类型和连接质量的信息。
安装
🌐 Installation
- npx expo install @react-native-community/netinfoIf you are installing this in an existing React Native app, make sure to install expo in your project. Then, follow the installation instructions provided in the library's README or documentation.
应用接口
🌐 API
要导入该库,请使用:
🌐 To import this library, use:
import NetInfo from '@react-native-community/netinfo';
如果你只想获取有关网络连接的信息一次,你可以使用:
🌐 If you want to grab information about the network connection just once, you can use:
NetInfo.fetch().then(state => { console.log('Connection type', state.type); console.log('Is connected?', state.isConnected); });
或者,如果你想订阅有关网络状态的更新(这样你就可以在网络状态发生变化时运行代码/执行操作),请使用:
🌐 Or, if you'd rather subscribe to updates about the network state (which then allows you to run code/perform actions anytime the network state changes) use:
const unsubscribe = NetInfo.addEventListener(state => { console.log('Connection type', state.type); console.log('Is connected?', state.isConnected); }); // To unsubscribe to these update, just use: unsubscribe();
访问 SSID
🌐 Accessing the SSID
要访问 ssid 属性(在 state.details.ssid 下可用),需要进行一些额外的配置步骤:
🌐 To access the ssid property (available under state.details.ssid), there are a few additional configuration steps:
- 使用
Location.requestForegroundPermissionsAsync()或Location.requestBackgroundPermissionsAsync()请求位置权限。
仅限 iOS
🌐 iOS only
-
在你的 app.json 中的
ios.entitlements下添加com.apple.developer.networking.wifi-info权限:app.json"ios": { "entitlements": { "com.apple.developer.networking.wifi-info": true } } -
在你应用的 App 标识符中勾选 访问 Wi-Fi 信息 选项,可以在这里找到。
-
使用
eas build --platform ios或npx expo run:ios重建你的应用。
了解更多
🌐 Learn more
获取有关 API 及其使用的完整信息。