How do I validate pure information in React Native iOS?

I need to test internet connection in iOS responsive mode

I would try the following code:

NetInfo.isConnected.fetch().then(isConnected => {
   console.log(isConnected);
});

      

which might work fine in case of reacting native Android app, But it always returns "false" in response on native iOS.

+3


source to share


1 answer


There is currently an open question about this in the answer native github .

You can see the discussion there, but in a nutshell - fetch

always returns false

, but you can work around it by listening for the connection changed event.

Sample code from there:

componentDidMount() {
    NetInfo.isConnected.addEventListener('change', this.handleConnectionChange);

    NetInfo.isConnected.fetch().done(
      (isConnected) => { this.setState({ status: isConnected }); }
    );
}

componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('change', this.handleConnectionChange);
}

handleConnectionChange = (isConnected) => {
        this.setState({ status: isConnected });
        console.log('is connected: ${this.state.status}');
}

      

Edit:



It looks like this question has already worked . In addition, the event has change

been renamed to connectionChange

. Updated workaround:

componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectionChange);

    NetInfo.isConnected.fetch().done(
      (isConnected) => { this.setState({ status: isConnected }); }
    );
}

componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectionChange);
}

handleConnectionChange = (isConnected) => {
        this.setState({ status: isConnected });
        console.log('is connected: ${this.state.status}');
}

      

Updated:

The event type has been change

deprecated. Let's consider the use of the event type connectionChange

.

+21


source







All Articles