LoginSignup
1
2

More than 5 years have passed since last update.

ionic-nativeを使ってandroidとiosでibeaconを使う

Last updated at Posted at 2018-12-04

ionic-nativeでandroid,ios双方でibeacon使ったときにハマったり理解できたことがあったのでここに書いておきます。

android,ios共通部

動かすにはbluetoothとgpsが必要なのでダイアログを表示して許可を得ましょう。

BLEプラグインをインストール
https://ionicframework.com/docs/native/ble/

ダイアログの例

//パッケージをインポート
import { BLE } from "@ionic-native/ble";

~省略~
 //ダイアログ表示
    this.ble.isEnabled().then(() => {
      console.log("bluetooth is enabled all G");
    }, () => {
      console.log("bluetooth is not enabled trying to enable it");
          this.ble.enable().then(() => {
              console.log("bluetooth got enabled hurray");
                }, () => {
                  console.log("user did not enabled");
          })
    });

gpsプラグインをインストール
https://ionicframework.com/docs/native/location-accuracy/

import { LocationAccuracy } from "@ionic-native/location-accuracy";

~省略~
 //ダイアログ表示
    this.locationAccuracy.canRequest().then((canRequest: boolean) => {
      if(canRequest) {
        // the accuracy option will be ignored by iOS
        this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
          () => console.log('Request successful'),
          error => console.log('Error requesting location permissions', error)
        );
      }
    });

上記のコードでダイアログが表示されます。

android側のコード

サンプルのコードそのままで動きます。
https://ionicframework.com/docs/native/ibeacon/
(プラグインインストールしてね)

ですが、ボタンを押したときだけビーコンを探したいときなど断続的に使いたい場合はモニタリングを止めてやり直させる必要があります。
this.ibeacon.stopMonitoringForRegion(BeaconRegion);

これを適当な場所に書いてやればいいです。

ios側のコード

こちらもほぼそのままで動きますがiosはandroid側と挙動が違います。
androidはモニタリングしたときからビーコン範囲内にいてもdidEnterRagionに入ってくれますがiosは入ってくれません。なのでdidStartMonitoringForRegionの中からrequestStateForRegionを呼び出せば自分が指定したregionの範囲内か範囲外かわかるのでこれを使います。(気づくのに半日かかりました)。

参考にしたところ

https://github.com/petermetz/cordova-plugin-ibeacon/issues/206
https://github.com/petermetz/cordova-plugin-ibeacon/issues/72
https://qiita.com/nosaka/items/5348dd5f8889d445d533
http://yoshiminu.tumblr.com/post/136513507383/ios-ibeacon%E3%81%AE%E3%81%A4%E3%81%BE%E3%82%8A%E3%81%A9%E3%81%93%E3%82%8D
http://enamelsystems.com/0011/

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2