Ionic 3 onNotificationClicked () не подписывается на плагин Cordova для геозоны - PullRequest
0 голосов
/ 18 мая 2018

Я сталкиваюсь с некоторыми проблемами при разработке простого приложения с подключаемым модулем геозон для Ionic 3. Это приложение должно выдавать уведомление, когда пользователь входит в забор, но когда пользователь нажимает на уведомление, уведомление должно открывать страницуотличается от корневой страницы.Я пытался подписать метод onNotificationClicked () плагина геозон, но он не работал.

Это код

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Geofence } from '@ionic-native/geofence';
import { Page2Page } from '../../pages/page2/page2';


@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController,
              private geofence: Geofence) {

    geofence.initialize().then(
    // resolved promise does not return a value
    () =>
    console.log('Geofence Plugin Ready'),
      (err) => console.log(err)
    )

  }
  ionViewDidLoad(){
    this.addGeofence();
      this.geofence.onNotificationClicked().subscribe(()=>{
        this.navCtrl.push(Page2Page);
      });
  }
  private addGeofence() {
  //options describing geofence
    let fence = {
      id: '69ca1b88-6fbe-4e80-a4d4-ff4d3748acdb', //any unique ID
      //nonna 44.921575, 9.970478
      latitude:       44.921575, //center of geofence radius
      longitude:      9.970478,
      radius:         100, //radius to edge of geofence in meters
      transitionType: 3, //see 'Transition Types' below
      notification: { //notification settings
          id:             1, //any unique ID
          title:          'You crossed a fence', //notification title
          text:           'You just arrived to pos1.', //notification body
          openAppOnClick: true //open app when notification is tapped

      }
    }

    let fence2 = { //44.929907, 9.900818
      id: '69ca1b88-6fbe-4e80-a4d4-ff4d3748acdb1', //any unique ID
      //nonna 44.921575, 9.970478
      latitude:       44.929907, //center of geofence radius
      longitude:      9.900818,
      radius:         100, //radius to edge of geofence in meters
      transitionType: 3, //see 'Transition Types' below
      notification: { //notification settings
          id:             2, //any unique ID
          title:          'You crossed a fence', //notification title
          text:           'You just arrived to pos2.', //notification body
          openAppOnClick: true //open app when notification is tapped
      }
    }
    let fence3 = { //44.896738, 9.965208
      id: '69ca1b88-6fbe-4e80-a4d4-ff4d3748acdb2', //any unique ID
      //nonna 44.921575, 9.970478
      latitude:       44.896738, //center of geofence radius
      longitude:      9.965208,
      radius:         100, //radius to edge of geofence in meters
      transitionType: 3, //see 'Transition Types' below
      notification: { //notification settings
          id:             3, //any unique ID
          title:          'You crossed a fence', //notification title
          text:           'You just arrived to pos3.', //notification body
          openAppOnClick: true //open app when notification is tapped
      }
    }

    this.geofence.addOrUpdate([fence, fence2, fence3]).then(
       () => console.log('Geofence added'),
       (err) => console.log('Geofence failed to add')
     );
  }
}

В документации я нашел эту строку кода, ноЯ не понимаю, как его использовать, кто-нибудь может объяснить мне, как это работает?

window.geofence.onNotificationClicked = function (notificationData) {
    console.log('App opened from Geo Notification!', notificationData);
};

1 Ответ

0 голосов
/ 14 июня 2018

После некоторого исследования я понял это.

Если вы посмотрите на этот вопрос , вы увидите, что вы можете добавить свойство data к уведомлению вашего забора.объект.Например:

this.fences.push(
  {
    id: id, // any unique ID
    latitude:       poiModel.coordinates.latitude, // center of geofence radius
    longitude:      poiModel.coordinates.longitude,
    radius:         poiModel.geofenceNotification.radius, // radius to edge of geofence in meters. Try increase the radius, 3 meters is not enough to catch any transition, try with 100 instead.
    transitionType: poiModel.geofenceNotification.transitionType, // see 'Transition Types' below
    notification: { // notification settings
      id:             count++, // any unique ID
      title:          poiModel.geofenceNotification.title, // notification title
      text:           poiModel.geofenceNotification.text, // notification body
      openAppOnClick: true, // open app when notification is tapped
      data: { poiId: id } // This data is received on app launch.
    }
  }
)

После добавления этих заборов к службе и т. Д. Вы можете отслеживать onNotificationClicked() на своем корневом компоненте (app.component.ts).Например:

this._geofence.initialize().then(
  // resolved promise does not return a value
  () => {
    console.log('Geofence Plugin Ready')

    this._geofence.onNotificationClicked()
    .subscribe(
      (resp) => {
        console.log("Notification clicked app.component.ts");
        console.log(resp)
      },
      (err) => console.error(err))

  }).catch((err) => console.error(err))

Если все прошло хорошо, вы должны увидеть, как ваш data вошел в консоль, и действовать соответствующим образом.Примечание: инициализация службы геозон должна выполняться в рамках проверки готовности платформы platform.ready().then((readySource) => this._geofence.initialize().then() {...

Результат в корневом компоненте (app.component.ts):

enter image description here

Плагин Ionic Geofence плохо документирован, воспользуйтесь документацией к плагину Cordova Geofence: https://github.com/cowbell/cordova-plugin-geofence

Примечание. На домашней странице (home.ts) он не работал.моя первая видимая страницаЯ предлагаю вам проверить это в app.component.ts.

...