How to detect internet connection on ionic?

0

I'm using Ionic 3 together with the ionic network plugin, I can detect when it's connected to an internet network by the plugin but I can not check if this connected network is internet or not, does anyone know how I can do this?

    
asked by anonymous 25.07.2018 / 23:56

1 answer

2

There is the plugin quoted in the documentation itself: link to install navigate to the project folder with cd e run the commands, as in the example:

cd /home/user/projeto
ionic cordova plugin add cordova-plugin-network-information
npm install --save @ionic-native/network

Then in src/app/app.module.ts add to the providers, for example:

import { Network } from '@ionic-native/network';

...

@NgModule({
  ...

  providers: [
    ...
    Network
    ...
  ]
  ...
})
export class AppModule { }

So where to use the module do this:

import { Network } from '@ionic-native/network';

constructor(private network: Network) { }

...

let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
    console.log('Desconectado da internet');
});

let connectSubscription = this.network.onConnect().subscribe(() => {
    console.log('Conectado a internet!');
});

For observers use:

disconnectSubscription.unsubscribe();
connectSubscription.unsubscribe();

Note that it is not because you are connected to a network or mobile network which means that your provider is sending you the internet (providing you), a simpler test would be to use HttRequest and check if you can access any service url which is of interest to you.

For example (it's in php but you can easily adapt) would create a simple page that would return anything, for example the word success :

<?php
echo 'success';

So the test would be something like:

import { HTTP } from '@ionic-native/http';

constructor(private http: HTTP) {}

...

this.http.get('http://meu-site.com/status.php', {}, {})
  .then(response => {
      if (response.data === 'success') {
          console.log('Serviço disponivel');
      }
  })
  .catch(error => {
    console.log('Serviço indisponivel');
    console.log("status:", error.status);
    console.log("descritivo:", error.error);
    console.log("headers:", error.headers);

  });
    
26.07.2018 / 00:08