How to check net Info in React Native iOS?

天涯浪子 提交于 2019-12-18 16:38:13

问题


I need to check Internet connection in react native iOS

I would try following code:

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

that can work fine in react native android application, But it always return 'false' in react native iOS .


回答1:


There is currently an open issue about this in react native's github.

You can see the discussion there, but in short - the fetch is always returning false, but you can work around it by listening to the connection changed event.

Code example 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:

Seems like this issue has been worked on. Also, change event was renamed to connectionChange. Updated workaround code:

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 change event type is deprecated. Consider using the connectionChange event type.



来源:https://stackoverflow.com/questions/43198978/how-to-check-net-info-in-react-native-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!