UNPKG

24.6 kBMarkdownView Raw
1
2# `@react-native-community/netinfo`
3
4[![CircleCI Status](https://img.shields.io/circleci/project/github/react-native-netinfo/react-native-netinfo/master.svg)](https://circleci.com/gh/react-native-netinfo/workflows/react-native-netinfo/tree/master) ![Supports Android, iOS, macOS, and Windows](https://img.shields.io/badge/platforms-android%20|%20ios%20|%20macos%20|%20windows-lightgrey.svg) ![MIT License](https://img.shields.io/npm/l/@react-native-community/netinfo.svg) [![Lean Core Extracted](https://img.shields.io/badge/Lean%20Core-Extracted-brightgreen.svg)](https://github.com/facebook/react-native/issues/23313)
5
6React Native Network Info API for Android, iOS, macOS & Windows. It allows you to get information on:
7
8* Connection type
9* Connection quality
10
11## Getting started
12Install the library using either Yarn:
13
14```
15yarn add @react-native-community/netinfo
16```
17
18or npm:
19
20```
21npm install --save @react-native-community/netinfo
22```
23
24#### Using React Native >= 0.60
25Linking the package manually is not required anymore with [Autolinking](https://github.com/react-native-community/cli/blob/master/docs/autolinking.md).
26
27- **iOS Platform:**
28
29 `$ npx pod-install` # CocoaPods on iOS needs this extra step
30
31- **Android Platform with Android Support:**
32
33 Using [Jetifier tool](https://github.com/mikehardy/jetifier) for backward-compatibility.
34
35 Modify your **android/build.gradle** configuration:
36 ```
37 buildscript {
38 ext {
39 buildToolsVersion = "28.0.3"
40 minSdkVersion = 16
41 compileSdkVersion = 28
42 targetSdkVersion = 28
43 # Only using Android Support libraries
44 supportLibVersion = "28.0.0"
45 }
46 ```
47
48- **Android Platform with AndroidX:**
49
50 Modify your **android/build.gradle** configuration:
51 ```
52 buildscript {
53 ext {
54 buildToolsVersion = "28.0.3"
55 minSdkVersion = 16
56 compileSdkVersion = 28
57 targetSdkVersion = 28
58 # Remove 'supportLibVersion' property and put specific versions for AndroidX libraries
59 androidXCore = "1.0.2"
60 // Put here other AndroidX dependencies
61 }
62 ```
63
64- **macOS Platform:**
65
66 Autolinking is not yet available on macOS. See the [Manual linking steps for macOS](#manual-linking-macos) below.
67
68#### Using React Native < 0.60
69
70You then need to link the native parts of the library for the platforms you are using. The easiest way to link the library is using the CLI tool by running this command from the root of your project:
71
72```
73react-native link @react-native-community/netinfo
74```
75
76If you can't or don't want to use the CLI tool, you can also manually link the library using the instructions below (click on the arrow to show them):
77
78<details>
79<summary>Manually link the library on iOS</summary>
80
81Either follow the [instructions in the React Native documentation](https://facebook.github.io/react-native/docs/linking-libraries-ios#manual-linking) to manually link the framework or link using [Cocoapods](https://cocoapods.org) by adding this to your `Podfile`:
82
83```ruby
84pod 'react-native-netinfo', :path => '../node_modules/@react-native-community/netinfo'
85```
86
87</details>
88
89<details id='manual-linking-macos'>
90<summary>Manually link the library on macOS</summary>
91
921. Open your project `.xcodeproj` on xcode.
93
942. Right click on the Libraries folder and select `Add files to "yourProjectName"`.
95
963. Add `RNCNetInfo.xcodeproj` (located at `node_modules/@react-native-community/react-native-netinfo/macos`) to your project Libraries.
97
984. Go to `Build Phases -> Link Binary with Libraries` and add: `libRNCNetInfo-macOS.a`.
99
100</details>
101
102<details>
103<summary>Manually link the library on Android</summary>
104
105Make the following changes:
106
107#### `android/settings.gradle`
108```groovy
109include ':react-native-community-netinfo'
110project(':react-native-community-netinfo').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/netinfo/android')
111```
112
113#### `android/app/build.gradle`
114```groovy
115dependencies {
116 ...
117 implementation project(':react-native-community-netinfo')
118}
119```
120
121#### `android/app/src/main/.../MainApplication.java`
122On top, where imports are:
123
124```java
125import com.reactnativecommunity.netinfo.NetInfoPackage;
126```
127
128Add the `NetInfoPackage` class to your list of exported packages.
129
130```java
131@Override
132protected List<ReactPackage> getPackages() {
133 return Arrays.asList(
134 new MainReactPackage(),
135 new NetInfoPackage()
136 );
137}
138```
139</details>
140
141<details>
142<summary>Manually link the library on Windows</summary>
143
144#### Link C++ implementation
145* Open the solution in Visual Studio for your Windows apps
146* Right click in the Explorer and click Add > Existing Project...
147* Navigate to `./<app-name>/node_modules/@react-native-community/netinfo/windows/RNCNetInfoCPP/` and add `RNCNetInfoCPP.vcxproj`
148* This time right click on your React Native Windows app under your solutions directory and click Add > Reference...
149* Check the `RNCNetInfoCPP` you just added and press ok
150* Open `pch.h`, add `#include "winrt/ReactNativeNetInfo.h"`
151* Open `App.cpp`, add `PackageProviders().Append(winrt::ReactNativeNetInfo::ReactPackageProvider());` before `InitializeComponent();`
152
153#### Link C# implementation
154* Open the solution in Visual Studio for your Windows apps
155* Right click in the Explorer and click Add > Existing Project...
156* Navigate to `./<app-name>/node_modules/@react-native-community/netinfo/windows/RNCNetInfo/` and add `RNCNetInfo.csproj`
157* This time right click on your React Native Windows app under your solutions directory and click Add > Reference...
158* Check the `RNCNetInfo` you just added and press ok
159* Open up `MainReactNativeHost.cs` for your app and edit the file like so:
160
161```diff
162+ using ReactNativeCommunity.NetInfo;
163......
164 protected override List<IReactPackage> Packages => new List<IReactPackage>
165 {
166 new MainReactPackage(),
167+ new RNCNetInfoPackage(),
168 };
169```
170
171</details>
172
173## React Native Compatibility
174To use this library you need to ensure you are using the correct version of React Native. If you are using a version of React Native that is lower than `0.57` you will need to upgrade that before attempting to use this library.
175
176| `@react-native-community/netinfo` version | Required React Native Version |
177| ----------------------------------------- | --------------------------------------------------------------------------------- |
178| `4.x.x` & `5.x.x` | `>= 0.60` or `>= 0.59` if using [Jetifier](https://github.com/mikehardy/jetifier) |
179| `3.x.x` | `>= 0.59` |
180| `2.x.x` | `>= 0.57` |
181| `1.x.x` | `>= 0.57` |
182
183## Browser Compatilibity
184The web implementation heavily depends on the [Network Information API](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API) which is still an is an experimental technology and thus it's not supported in every browser.
185If this API is not available the library will safely fallback to the old [onLine](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine) property and return basic connection information.
186
187## Migrating from the core `react-native` module
188This module was created when the NetInfo was split out from the core of React Native. To migrate to this module you need to follow the installation instructions above and then change you imports from:
189
190```javascript
191import { NetInfo } from "react-native";
192```
193
194to:
195
196```javascript
197import NetInfo from "@react-native-community/netinfo";
198```
199
200Note that the API was updated after it was extracted from NetInfo to support some new features, however, the previous API is still available and works with no updates to your code.
201
202## Usage
203Import the library:
204
205```javascript
206import NetInfo from "@react-native-community/netinfo";
207```
208
209Subscribe to network state updates:
210
211```javascript
212// Subscribe
213const unsubscribe = NetInfo.addEventListener(state => {
214 console.log("Connection type", state.type);
215 console.log("Is connected?", state.isConnected);
216});
217
218// Unsubscribe
219unsubscribe();
220```
221
222Get the network state once:
223
224```javascript
225NetInfo.fetch().then(state => {
226 console.log("Connection type", state.type);
227 console.log("Is connected?", state.isConnected);
228});
229```
230
231## API
232* **Types:**
233 * [`NetInfoState`](#netinfostate)
234 * [`NetInfoStateType`](#netinfostatetype)
235 * [`NetInfoCellularGeneration`](#netinfocellulargeneration)
236* **Methods:**
237 * [`fetch()`](#fetch)
238 * [`addEventListener()`](#addeventlistener)
239 * [`useNetInfo()`](#usenetinfo)
240
241### Types
242
243#### `NetInfoState`
244Describes the current state of the network. It is an object with these properties:
245
246| Property | Type | Description |
247| --------------------- | --------------------------------------- | -------------------------------------------------------------------------------------------------- |
248| `type` | [`NetInfoStateType`](#netinfostatetype) | The type of the current connection. |
249| `isConnected` | `boolean`, `null` | If there is an active network connection. If unknown defaults to `null`. |
250| `isInternetReachable` | `boolean`, `null` | If the internet is reachable with the currently active network connection. If unknown defaults to `null` |
251| `isWifiEnabled` | `boolean` | *(Android only)* Whether the device's WiFi is ON or OFF. |
252| `details` | | The value depends on the `type` value. See below. |
253
254The `details` value depends on the `type` value.
255
256##### `type` is `none` or `unknown`
257
258`details` is `null`.
259
260##### `type` is `wifi`
261
262`details` has these properties:
263
264| Property | Platform | Type | Description |
265| ----------------------- | --------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------- |
266| `isConnectionExpensive` | Android, iOS, macOS, Windows, Web | `boolean` | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
267| `ssid` | Android, iOS (not tvOS) | `string` | The SSID of the network. May not be present, `null`, or an empty string if it cannot be determined. **On iOS, make sure your app meets at least one of the [following requirements](https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo?language=objc#discussion). On Android, you need to have the `ACCESS_FINE_LOCATION` permission in your `AndroidManifest.xml` and accepted by the user**. |
268| `bssid` | Android, iOS (not tvOS) | `string` | The BSSID of the network. May not be present, `null`, or an empty string if it cannot be determined. **On iOS, make sure your app meets at least one of the [following requirements](https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo?language=objc#discussion). On Android, you need to have the `ACCESS_FINE_LOCATION` permission in your `AndroidManifest.xml` and accepted by the user**. |
269| `strength` | Android | `number` | An integer number from `0` to `100` for the signal strength. May not be present if the signal strength cannot be determined. |
270| `ipAddress` | Android, iOS, macOS | `string` | The external IP address. Can be in IPv4 or IPv6 format. May not be present if it cannot be determined. |
271| `subnet` | Android, iOS, macOS | `string` | The subnet mask in IPv4 format. May not be present if it cannot be determined. |
272| `frequency` | Android | `number` | Network frequency. Example: For 2.4 GHz networks, the method will return 2457. May not be present if it cannot be determined. |
273
274##### `type` is `cellular`
275
276`details` has these properties:
277
278| Property | Platform | Type | Description |
279| ----------------------- | --------------------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
280| `isConnectionExpensive` | Android, iOS, macOS, Windows, Web | `boolean` | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
281| `cellularGeneration` | Android, iOS, Windows | [`NetInfoCellularGeneration`](#netinfocellulargeneration) | The generation of the cell network the user is connected to. This can give an indication of speed, but no guarantees. |
282| `carrier` | Android, iOS | `string` | The network carrier name. May not be present or may be empty if none can be determined. |
283
284##### `type` is `bluetooth`, `ethernet`, `wimax`, `vpn`, or `other`
285
286`details` has these properties:
287
288| Property | Type | Description |
289| ----------------------- | --------- | ------------------------------------------------------------------------------------------------------ |
290| `isConnectionExpensive` | `boolean` | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
291
292#### `NetInfoStateType`
293Describes the current type of network connection. It is an enum with these possible values:
294
295| Value | Platform | Description |
296| ----------- | --------------------------------- | ---------------------------------------------------------- |
297| `none` | Android, iOS, macOS, Windows, Web | No network connection is active |
298| `unknown` | Android, iOS, macOS, Windows, Web | The network state could not or has yet to be be determined |
299| `cellular` | Android, iOS, Windows, Web | Active network over cellular |
300| `wifi` | Android, iOS, macOS, Windows, Web | Active network over Wifi |
301| `bluetooth` | Android, Web | Active network over Bluetooth |
302| `ethernet` | Android, macOS, Windows, Web | Active network over wired ethernet |
303| `wimax` | Android, Web | Active network over WiMax |
304| `vpn` | Android | Active network over VPN |
305| `other` | Android, iOS, macOS, Windows, Web | Active network over another type of network |
306
307#### `NetInfoCellularGeneration`
308Describes the current generation of the `cellular` connection. It is an enum with these possible values:
309
310| Value | Description |
311| --------- | ----------------------------------------------------------------------------------------------------------------- |
312| `null` | Either we are not currently connected to a cellular network or type could not be determined |
313| `2g` | Currently connected to a 2G cellular network. Includes CDMA, EDGE, GPRS, and IDEN type connections |
314| `3g` | Currently connected to a 3G cellular network. Includes EHRPD, EVDO, HSPA, HSUPA, HSDPA, and UTMS type connections |
315| `4g` | Currently connected to a 4G cellular network. Includes HSPAP and LTE type connections |
316
317#### `NetInfoConfiguration`
318The configuration options for the library.
319
320| Property | Type | Description |
321| ---------------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
322| `reachabilityUrl` | `string` | The URL to call to test if the internet is reachable. Only used on platforms which do not supply internet reachability natively. |
323| `reachabilityTest` | `(response: Response) => boolean` | A function which is passed the `Response` from calling the reachability URL. It should return `true` if the response indicates that the internet is reachable. Only used on platforms which do not supply internet reachability natively. |
324| `reachabilityShortTimeout` | `number` | The number of milliseconds between internet reachability checks when the internet was not previously detected. Only used on platforms which do not supply internet reachability natively. |
325| `reachabilityLongTimeout` | `number` | The number of milliseconds between internet reachability checks when the internet was previously detected. Only used on platforms which do not supply internet reachability natively. |
326| `reachabilityRequestTimeout` | `number` | The number of milliseconds that a reachability check is allowed to take before failing. Only used on platforms which do not supply internet reachability natively. |
327
328### Methods
329
330#### `configure()`
331
332Configures the library with the given configuration. You only need to supply the properties which you want to change from the default values.
333
334Note that calling this will stop all previously added listeners from being called again. It is best to call this right when your application is started to avoid issues.
335
336**Example:**
337```javascript
338NetInfo.configure({
339 reachabilityUrl: 'https://clients3.google.com/generate_204',
340 reachabilityTest: async (response) => response.status === 204,
341 reachabilityLongTimeout: 60 * 1000, // 60s
342 reachabilityShortTimeout: 5 * 1000, // 5s
343 reachabilityRequestTimeout: 15 * 1000, // 15s
344});
345```
346
347#### `addEventListener()`
348
349Subscribe to connection information. The callback is called with a parameter of type [`NetInfoState`](README.md#netinfostate) whenever the connection state changes. Your listener will be called with the latest information soon after you subscribe and then with any subsequent changes afterwards. You should not assume that the listener is called in the same way across devices or platforms.
350
351| Parameter | Type | Description |
352| ----------- | ------------------------------------------------------------- | ----------------------------------------------------------------------- |
353| `listener` | `(state: `[`NetInfoState`](README.md#netinfostate))` => void` | The listener which will be called whenever the connection state changes |
354
355**Example:**
356```javascript
357// Subscribe
358const unsubscribe = NetInfo.addEventListener(state => {
359 console.log("Connection type", state.type);
360 console.log("Is connected?", state.isConnected);
361});
362
363// Unsubscribe
364unsubscribe();
365```
366
367#### `useNetInfo()`
368
369A [React Hook](https://reactjs.org/docs/hooks-intro.html) which can be used to get access to the latest state. It returns a hook with the [`NetInfoState`](README.md#netinfostate) type.
370
371**Example:**
372```jsx
373import {useNetInfo} from "@react-native-community/netinfo";
374
375const YourComponent = () => {
376 const netInfo = useNetInfo();
377
378 return (
379 <View>
380 <Text>Type: {netInfo.type}</Text>
381 <Text>Is Connected? {netInfo.isConnected.toString()}</Text>
382 </View>
383 );
384};
385```
386
387You can optionally send configuration when setting up the hook. Note that configuration is global for the library, so you shouldn't send different configuration for different hooks. It is instead recommended that you called `NetInfo.configure()` once when your project starts. The hook option is only provided as a convinience.
388
389```jsx
390const YourComponent = () => {
391 const netInfo = useNetInfo({
392 reachabilityUrl: 'https://clients3.google.com/generate_204',
393 reachabilityTest: async (response) => response.status === 204,
394 reachabilityLongTimeout: 60 * 1000, // 60s
395 reachabilityShortTimeout: 5 * 1000, // 5s
396 reachabilityRequestTimeout: 15 * 1000, // 15s
397 });
398
399 // ...
400};
401```
402
403#### `fetch()`
404
405Returns a `Promise` that resolves to a [`NetInfoState`](README.md#netinfostate) object.
406
407**Example:**
408```javascript
409NetInfo.fetch().then(state => {
410 console.log("Connection type", state.type);
411 console.log("Is connected?", state.isConnected);
412});
413```
414
415You can optionally send an `interface` string so the `Promise` resolves to a [`NetInfoState`](README.md#netinfostate) from the [`NetInfoStateType`](#netinfostatetype) indicated in `interface` argument.
416
417```javascript
418NetInfo.fetch("wifi").then(state => {
419 console.log("SSID", state.details.ssid);
420 console.log("BSSID", state.details.bssid);
421 console.log("Is connected?", state.isConnected);
422});
423```
424
425## Troubleshooting
426
427### Errors when building on Android
428
429This library was migrated from using the support library to AndroidX in version `4.0.0`. All of your depenencies must be using either the support library *or* AndroidX. Using a mixture of the two is not possible.
430
431From React Native 0.60 AndroidX is used by default.
432
433If you need to either convert this library back to the support library (to use an older React Native version) or convert other libraries forward to use AndroidX (if they have not been updated yet), you can use the [Jetifier](https://github.com/mikehardy/jetifier) tool.
434
435### Errors while running Jest tests
436
437If you do not have a Jest Setup file configured, you should add the following to your Jest settings and create the `jest.setup.js` file in project root:
438
439```js
440setupFiles: ['<rootDir>/jest.setup.js']
441```
442
443You should then add the following to your Jest setup file to mock the NetInfo Native Module:
444
445```js
446import mockRNCNetInfo from '@react-native-community/netinfo/jest/netinfo-mock.js';
447
448jest.mock('@react-native-community/netinfo', () => mockRNCNetInfo);
449```
450
451### Issues with the iOS simulator
452
453There is a [known](http://openradar.appspot.com/14585459) [issue](http://www.openradar.appspot.com/29913522) with the iOS Simulator which causes it to not receive network change notifications correctly when the host machine disconnects and then connects to Wifi. If you are having issues with iOS then please test on an actual device before reporting any bugs.
454
455## Maintainers
456
457* [Matt Oakes](https://github.com/matt-oakes) - [Freelance React Native Developer](http://mattoakes.net)
458* [Mike Diarmid](https://github.com/salakar) - [Invertase](https://invertase.io)
459
460## Contributing
461
462Please see the [contributing guide](/CONTRIBUTING.md).
463
464## License
465
466The library is released under the MIT license. For more information see [`LICENSE`](/LICENSE).