petermetz / cordova-plugin-ibeacon

An iBeacon plugin for Phonegap / Cordova 3.x and upwards. Supports both iOS and Android (contributions are welcome)
Apache License 2.0
728 stars 372 forks source link

How to search beacon in background #247

Open murugesh08 opened 8 years ago

murugesh08 commented 8 years ago

Hi,I have tried to search beacon in background when the app is in inactive state and I also referred a link "https://github.com/nraboy/ng-cordova-beacon/issues/4". Below code startMonitoringForRegion doesn't call the "didEnterRegion" and "didExitRegion".please help me how to do background search or monitoring My code snippet:-

.controller("ExampleController", function($scope, $rootScope, $ionicPlatform, $cordovaBeacon) {
            console.log("start")
            console.log($cordovaBeacon)

    $scope.beacons = {};

    $ionicPlatform.ready(function() {

        $cordovaBeacon.requestAlwaysAuthorization();

        $rootScope.$on("$cordovaBeacon:didEnterRegion", function(event, pluginResult) {

            var uniqueBeaconKey;
            for(var i = 0; i < pluginResult.beacons.length; i++) {
                uniqueBeaconKey = pluginResult.beacons[i].uuid + ":" + pluginResult.beacons[i].major + ":" + pluginResult.beacons[i].minor;
                $scope.beacons[uniqueBeaconKey] = pluginResult.beacons[i];
                       console.log("ibeacon elements")
                       console.log(pluginResult.beacons)
            }
            $scope.$apply();
        });

         $rootScope.$on("$cordovaBeacon:didExitRegion", function(event, pluginResult) {
        console.log("ibeacondidExitRegion")
     // $cordovaVibration.vibrate(500);
            });
        $cordovaBeacon.startMonitoringForRegion($cordovaBeacon.createBeaconRegion("estimote", "uuid"));

       // 
    });
});

`
jonasty19 commented 8 years ago

@murugesh08 It's really easy to monitor in the background on an Android device, as they have way less restrictions. For iOS, however, there are a few gotchas that you need to go through. Have you gone into xCode and set the "Background Modes" properly? If you open your app in xCode after you have built it with cordova, you should be able to get to the "Capabilities" tab (Click on the name of your project in the upper part of the left-side bar), then click on the "Capabilities" tab. Scroll down to "Background modes" and make sure you have "Location updates" turned on. For good measure, I also clicked on "Uses Bluetooth LE accessories" and "Acts as a Bluetooth LE accessory" with the eventual thought that I would actually test to see if they were necessary. Anyways, hope this solves your problem.

brunocarneiro commented 8 years ago

Hi All,

I'm facing the same issue. I cannot monitor a region on iOS even using the sample code written in README.md. I also made all the recommendations @jonasty19 told. However it does not work. If it helps, although monitoring is not working, I can range beacons using this plugin. Does anyone have a sample app showing background monitoring working in iOS and Android? Here is my code:

` var logToDom = function (message) { console.log("Going to send a monitoring message"); try{ cordova.plugins.notification.local.schedule({text: message}); } catch(e){ console.log("Error ",e) } };

    var delegate = new cordova.plugins.locationManager.Delegate();

    delegate.didDetermineStateForRegion = function (pluginResult) {

        logToDom('[DOM] didDetermineStateForRegion: ' + JSON.stringify(pluginResult));

        cordova.plugins.locationManager.appendToDeviceLog('[DOM] didDetermineStateForRegion: '
            + JSON.stringify(pluginResult));
    };

    delegate.didStartMonitoringForRegion = function (pluginResult) {
        console.log('didStartMonitoringForRegion:', pluginResult);

        logToDom('didStartMonitoringForRegion:' + JSON.stringify(pluginResult));
    };

    delegate.didRangeBeaconsInRegion = function (pluginResult) {
        logToDom('[DOM] didRangeBeaconsInRegion: ' + JSON.stringify(pluginResult));
    };

    var uuid = '0428c59e-25b7-4e9d-b3cd-d126a46e6e9d';
    var identifier = 'zapt.tech';
    var beaconRegion = new cordova.plugins.locationManager.BeaconRegion(identifier, uuid);

    console.log("Going to monitor region");
    cordova.plugins.locationManager.setDelegate(delegate);

    // required in iOS 8+
    cordova.plugins.locationManager.requestWhenInUseAuthorization();
    // or cordova.plugins.locationManager.requestAlwaysAuthorization()

    cordova.plugins.locationManager.startMonitoringForRegion(beaconRegion)
        .fail(function(e) { console.error("Error while trying to start monitoring",e); })
        .done();

    var uuid = '0428c59e-25b7-4e9d-b3cd-d126a46e6e9d';
    var identifier = 'zapt.tech';
    var beaconRegion = new cordova.plugins.locationManager.BeaconRegion(identifier, uuid);

    cordova.plugins.locationManager.startMonitoringForRegion(beaconRegion)
        .fail(function(e) { console.error("Error while trying to start monitoring",e); })
        .done();

`

jonasty19 commented 8 years ago

I have also had some problems where onEnter does not work if you are already in the region before you start monitoring...You could try to start the app outside of the range of the beacon, and then walk into the range once it has started. There is some command (I can't think of it right now) that initializes this and will reset the onEnter to work, even if you are already within range.

I would research it myself, but I don't have the time right now. Hopefully this helps.

codingjam commented 8 years ago

Were you able to get it working? I am facing the similar issue, enter/exit region events are not getting called when the app is killed. It works fine when the app is pushed to the background but NOT killed. My code is very similar to the @brunocarneiro code. I thought monitoring in background even when app is killed works automatically in IOS after you have started monitoring regions at least once in foreground. I have another Xamarin app and the monitoring works fine in it when app is killed. It is the same concept, register a delegate with locationmanager and the IOS takes care of monitoring after that.

VitorHFLopes commented 7 years ago

@codingjam can you please share with us your solution for background monitoring with this xamarin app?

codingjam commented 7 years ago

@VitorHFLopes I did not do anything special in Xamarin app to make the monitoring work in background. IOS automatically takes care of it. Make sure you have the authorization, and set the appropriate key value in info.plist

       <key>NSLocationWhenInUseUsageDescription</key>
    <string>You are about to use location</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>Location used behind the scenes</string>
               ```
               _locationManager = new CLLocationManager();
                _locationManager.Delegate = new CoreLocation();
                _locationManager.RequestAlwaysAuthorization();
                _locationManager.RequestWhenInUseAuthorization(); 

`And when you create a Region set the following properties to true.`
        beaconRegion = new CLBeaconRegion(new NSUuid(Globals.BroadcastUUID), Globals.Region);
        beaconRegion.NotifyEntryStateOnDisplay = true;
        beaconRegion.NotifyOnEntry = true;
        beaconRegion.NotifyOnExit = true;
VitorHFLopes commented 7 years ago

@codingjam I've made a concept mistake, background is different when you kill the app (remove from task switcher). I can find beacons in background with android and iOS, but what I need is a service to keep watching beacons when the app is killed. After a research I couldn't find any way to do that with Ionic for example, this just can be done only with native code :/ If you know something that can help feel free to share and if I saying something wrong, please correct me, thanks for your answer!!

cagb80 commented 5 years ago

I tried everything... we need to install Background Plugin

giladrom commented 5 years ago

@cagb80 This works out of the box on iOS. In Android, you will need to write native code.

cagb80 commented 5 years ago

@cagb80 This works out of the box on iOS. In Android, you will need to write native code. I tried in both... is running like a Charm... Im using Ionic 4.12.0

giladrom commented 5 years ago

You will not be able to submit your app to the app store if using this plugin, FYI.

cagb80 commented 5 years ago

Jum... Why tell me about!