Ali Ghassan
Ali Ghassan

Reputation: 1180

check network status using network native

I am working on ionic 4 project. My project is getting data json from url . l am try to use Network native for ionic to check internet connections for my app .But l got nothing to show. No data and no alert to show .

 constructor(private http: HTTP, public loadingController: LoadingController,private network: Network,
   public alertController : AlertController, public platform : Platform) {


    // watch network for a disconnection
    let disconnectSubscription = this.network.onDisconnect().subscribe(() => {

      this.AlertNet()

    });

    // stop disconnect watch
    disconnectSubscription.unsubscribe();


    // watch network for a connection
    let connectSubscription = this.network.onConnect().subscribe(() => {
      console.log('network connected!');


      this.getData()

      setTimeout(() => {
        if (this.network.type === 'wifi') {
          console.log('we got a wifi connection, woohoo!');
        }
      }, 3000);
    });

    // stop connect watch
    connectSubscription.unsubscribe();



       }

      async getData() {


          const loading = await this.loadingController.create({
            message: 'Loading'
          });
          await loading.present();
          this.http.get('/v1/airport.json?code=krt', {}, {})
          .then(data => {

            this.test = JSON.parse(data.data);
            const parsed = JSON.parse(data.data);


          }), err=>{
            this.test =err
            loading.dismiss()
          }



      }


     async AlertNet(){

      const alert = await this.alertController.create({
        header: 'Alert',
        subHeader: 'No internet',
        message: 'You do not have an Internet connection. Please check your connection status',
        buttons: [{
          text: "Ok",
          handler: () => { this.platform.backButton.subscribe(()=>{
            navigator['app'].exitApp();
        });
       }
        }]    
        });

      await alert.present();

     }

Upvotes: 0

Views: 2565

Answers (3)

Hammad Ahmad
Hammad Ahmad

Reputation: 204

Don't use plugins for network checking, I got a very very and very easy way to check if the user has Internet connection or not, so all we have to do is that to use this:

if (navigator.onLine) {
   console.log('Internet is connected');
} else {
   console.log('No internet connection');
}

At here navigator is not a variable created by me. The navigator. onLine property provides a boolean value whether or not the user is connected to the Internet. … Browser and real device also supports online and offline events whenever the browser is goes offline or comes online.

This is the very easy and working way, I’m sure it will help.

Upvotes: 2

Ali Ghassan
Ali Ghassan

Reputation: 1180

Finally l found it the problem . Several failed attempts have reached a conclusion :

constructor(private http: HTTP, public loadingController: LoadingController,public network: Network,

   public alertController : AlertController, public toastController : ToastController) {


    if (this.network.type == 'none'){
      this.AlertNet()


    }else if(this.network.type === 'wifi'){

      this.getData()
    }

    this.network.onConnect().subscribe(()=> {
      if(network.Connection.WIFI){

        this.presentToastWithOptions()

      }
    });

    this.network.onDisconnect().subscribe(()=> {
      this.presentToast()
    });

   }
   async presentToast() {
    const toast = await this.toastController.create({
      message: 'You dont have internet connection :(',
      duration: 2000
    });
    toast.present();
  }

  async presentToastWithOptions() {
    const toast = await this.toastController.create({
      message: 'Internet connection is back :)',
      showCloseButton: true,
      position: 'top',
      closeButtonText: 'Done'
    });
    toast.present();
  }

 async AlertNet(){

  const alert = await this.alertController.create({
    header: 'Alert',
    subHeader: 'No internet',
    message: 'You do not have an Internet connection. Please check your connection status',
    buttons: [{
      text: "Ok"


    }]    
    });

  await alert.present();

 }

If you use onConnect and onDisconnect they are only working for detected connection . example if you are inside app and you switch off wifi onDisconnect he will work to detected that and onConnect same work if you switch on wifi or Mobile data .

if you want to detected your connection for first run for your app you can do with network.type

   if (this.network.type == 'none'){
      this.AlertNet()


    }else if(this.network.type === 'wifi'){

      this.getData()
    }

when l used this code above and run app he is start to check my phone if he has internet connection or net . if he doesn't has he will show me alert immediately .

Upvotes: 4

AVJT82
AVJT82

Reputation: 73377

Move your alert controller code to its own async function, since you cannot use await without async, as you have already established. Also I would suggest to place the connection code inside platform.ready so that we know for sure it has loaded:

constructor(private platform: Platform, private network: Network ......) {
  this.platform.ready().then(() => {
    let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
      this.openAlert();
    });

  // watch network for a connection
  let connectSubscription = this.network.onConnect().subscribe(() => {
    console.log('network connected!');
    // We just got a connection but we need to wait briefly
    // before we determine the connection type. Might need to wait.
    // prior to doing any api requests as well.
    setTimeout(() => {
      if (this.network.type === 'wifi') {
        console.log('we got a wifi connection, woohoo!');
        this.getData();
      }
    }, 3000);
  });
  });
}

async openAlert() {
  const alert = await this.alertController.create({
    header: 'Alert',
    subHeader: 'No internet',
    message: 'You do not have an Internet connection.'
    buttons: [{
      text: "Ok",
      handler: () => { 
        // you are propbably going to run into issues here...
        this.platform.backButton.subscribe(() => {
          navigator['app'].exitApp();
        });
       }
      }]    
    });
  await alert.present();
}

This seems to work just fine when testing, starting app when having connection on, then switching it off, and back on.

enter image description here

If you want, when coming into component, check that there is a connection, then do a check for this.network.type !== 'none' (connection exists)

Upvotes: 2

Related Questions