提供对网络信息的访问的跨平台 API。
@react-native-community/netinfo
允许你获取有关连接类型和连接质量的信息。
¥@react-native-community/netinfo
allows you to get information about connection type and connection quality.
¥Installation
-
npx expo install @react-native-community/netinfo
If you are installing this in an existing React Native app (bare workflow), start by installing expo
in your project. Then, follow the additional instructions as mentioned by library's README under "Installation in bare React Native projects" section.
要导入该库,请使用:
¥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();
¥Accessing the SSID
要访问 ssid
属性(在 state.details.ssid
下可用),需要执行一些额外的配置步骤:
¥To access the ssid
property (available under state.details.ssid
), there are a few additional configuration steps:
¥Android and iOS
使用 Location.requestForegroundPermissionsAsync()
或 Location.requestBackgroundPermissionsAsync()
请求位置权限。
¥Request location permissions with Location.requestForegroundPermissionsAsync()
or Location.requestBackgroundPermissionsAsync()
.
¥iOS only
将 com.apple.developer.networking.wifi-info
权利添加到 ios.entitlements
下的 app.json 中:
¥Add the com.apple.developer.networking.wifi-info
entitlement to your app.json under ios.entitlements
:
"ios": {
"entitlements": {
"com.apple.developer.networking.wifi-info": true
}
}
选中应用的应用标识符 可以在这里找到 中的访问 Wi-Fi 信息框。
¥Check the Access Wi-Fi Information box in your app's App Identifier, which can be found here.
使用 eas build --platform ios
或 npx expo run:ios
重建你的应用。
¥Rebuild your app with eas build --platform ios
or npx expo run:ios
.
有关 API 和使用的更多信息,请参阅 react-native-netinfo
文档。
¥For more information on API and usage, see react-native-netinfo
documentation.