can I scan for beacons without specifying "region" is swift? - ios

I have this code to scan beacons
var closetBeacon: NSUUID?
let locationManager = CLLocationManager()
let region = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D")!, identifier: "my_beacons")
func authorizeBeaconScan() -> Void{
locationManager.delegate = self
if (CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedWhenInUse) {
locationManager.requestWhenInUseAuthorization()
}
locationManager.startRangingBeaconsInRegion(region)
}
I understand region is supposed to filter only beacons I care about.
1) If I have few beacons I care about, how do I pass them all to CLBeaconRegion(..)?
2) can I scan for beacon without specifying region?

You have to have UUID of beacons to scan.
Without UUID you can't scan beacons.
1) You can scan all beacons of same UUID for region by only specifying UUID.
2) You can scan specific beacons of one group having common major value by specifying UUID and major value.
3) You can also scan for specific beacon by using UUID, major and minor value of that beacon.
You have to have at-least one UUID of beacon to create region and start scanning it.

Related

Are there any other solutions in Monitoring BeaconRegion Immediately?

I make an application with iBeacon.
And I decide to use CoreLocation and Ranging.
But, I think Ranging use too much energy.
As an alternative to Ranging, I tried to use Monitoring.
Then, I profile Ranging's usage energy level and Monitoring's usage energy level.
Ranging use about 2 energy usage levels more than Monitoring
Result: (Ranging's level: 10/20, Monitoring's level: 8/20)
But, Monitoring doesn't called didExit or didDetermineState immediately.
I want My app has a Real-Time as Ranging.
My Solution:
Monitoring Start
If I enter Monitoring region, I start Ranging
If I exit region, ranging result is nil, and stop Ranging
Monitoring Stop and Start.
Monitoring doesn't called exit or determineState method immediately.
But, I discovered stop and rerun monitoring make my application has Real-Time.
I think that solution reduce energy usage when standby.
And It Actually Working!
▼ Here is my Code.
class Service: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate, CLLocationManagerDelegate{
private let constraint = CLBeaconIdentityConstraint(uuid: Constants.beaconUUID!,
major: Constants.beaconMajor,
minor: Constants.beaconMinor)
private let region = CLBeaconRegion(beaconIdentityConstraint:
CLBeaconIdentityConstraint(uuid: Constants.beaconUUID!,
major: Constants.beaconMajor,
minor: Constants.beaconMinor),
identifier: Constants.beaconIdentifier)
var locationManager: CLLocationManager!
override init() {
super.init()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
}
}
extension Service {
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
if manager.authorizationStatus == .authorizedAlways {
region.notifyOnExit = true
region.notifyOnEntry = true
region.notifyEntryStateOnDisplay = true
manager.startMonitoring(for: region)
}
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
if state == .inside {
didEnterEvents(manager)
}
}
func locationManager(_ manager: CLLocationManager, didRange beacons: [CLBeacon], satisfying beaconConstraint: CLBeaconIdentityConstraint) {
if beacons.first == nil {
didExitEvents(manager)
stopAndRerunMonitoring(manager, for: region)
}
}
}
extension Service {
private func stopAndRerunMonitoring(_ manager: CLLocationManager, for region: CLRegion) {
print("reboot!")
manager.stopMonitoring(for: region)
manager.startMonitoring(for: region)
}
private func didEnterEvents(_ manager: CLLocationManager) {
print("inside")
manager.startRangingBeacons(satisfying: constraint)
}
private func didExitEvents(_ manager: CLLocationManager) {
print("outside")
manager.stopRangingBeacons(satisfying: constraint)
}
}
I know my solution is terrible.
But I can't find any other solution.
Plz, Can you find any other better solution?
etc:
didEnter and didExit called determineState method.
I need to call requestState() method in other code. so I write a Enter event logic in determineState method.
You need Real-Time?
Yes, because i will make safety system with beacon. So My application's requirements has Real-Time.
I need Real-Time regioning and less energy usage.
The approach you describe of starting ranging on region entry and stopping it on region exit is not "terrible". It is in fact quite common. It is often used to determine the exact identifiers of the beacons detected, which would otherwise not be possible by monitoring alone.
For your use case, it is also true that ranging while inside a region will expedite the region exit event, because it forces a constant Bluetooth scan rather than relying on the slower hardware filters used for monitoring. While ranging is active, region exits come 30 seconds after the beacon was last detected.
For this to be a practical solution, you must take into account background behavior:
Unless you do special tricks, iOS won't let you range for more than a few seconds when the screen is off. As soon as ranging stops, you lose the expedited region exits.
While the screen is on, there is no point in saving battery by not ranging all the time, because the illuminated screen uses over 100x as much battery as the constant Bluetooth scan of ranging.
To get any benefit from the technique you describe, you must extend the ranging time in the background as described in my blog post here. Be aware that since I wrote that article, Apple has reduced the time you can extend ranging in the background from 180 seconds to 30 seconds, which may not be enough for your needs. You can get unlimited background ranging by:
Add the location background mode to Info.plist
Obtain "always" location permission from the user. It is not sufficient to get "when in use" permission.
Start a background task as described here: http://www.davidgyoungtech.com/2014/11/13/extending-background-ranging-on-ios
Request 3km location updates from CoreLocation. This will keep the app running in the background without extra battery drain from GPS, as 3km accuracy only uses the cell radio You don't need to do anything with these results. You just need to request them to keep the app alive.

Get distance from eddystone beacon

I am implementing beacons in my app with google beacon platform. Currently, beacon can be detected from a long range. I need to limit the range of detection which is quite not possible right now. Other option I am considering to detect the distance between iPhone and beacon. Is there anything provided by google or open-source SDK which can help me achieving the desired behaviour?
The documentation is pretty sparse, but I have open source code here detecting Eddystone on iOS and ranging beacons with it.
Here is an example of how you use it to detect Eddystone-UID:
var scanner: RNLBeaconScanner?
scanner = RNLBeaconScanner.shared()
scanner?.startScanning()
// Execute this code periodically (every second or so) to view the beacons detected
if let detectedBeacons = scanner?.trackedBeacons() as? [RNLBeacon] {
for beacon in detectedBeacons {
if (beacon.beaconTypeCode.intValue == 0x00 && beacon.serviceUuid.intValue == 0xFEAA) {
// this is eddystone uid
NSLog("Detected EDDYSTONE-UID with namespace %# instance %#", beacon.id1, beacon.id2)
NSLog("The beacon is about %.1f meters away", beacon.distance)
}
}
}

If two iBeacons are close together, can one signal override another on the way to a device (iPhone)

I have a simple question that I can't find the answer to. I am testing an app with some iBeacons, and I observe that one of my iBeacons never begins to range...the region is monitored, its just not being detected. When I look at console output the other beacons get detected, and then a few seconds later, another beacon gets detected, but it has the same UUID/major/minor/identifier values as one of the other locations already detected.
So all but one of the beacons get recognized and their states get determined. Then it appears that one of the beacons that has already been determined, gets determined again (same info). These beacons are somewhat close together (about a meter apart in x, y but on different floors (2nd floor and 3rd floor), and I'm wondering if one beacon signal could override another...which would be why I am seeing the info for one of the beacons twice. Otherwise I'm not sure why I can't detect this one beacon.
Here is some of my code, I've combed over it and I can't find anything wrong with human error stuff like entering correct major/minor/UUID values.
This function gets called to start monitoring the beacons:
func monitorBeacons() {
print("monitorBeacons()")
if CLLocationManager.isMonitoringAvailable(for:
CLBeaconRegion.self) {
print("monitorBeacons().monitoringIsAvailable")
// Match all beacons with the specified UUID
let proximityUUIDA = UUID(uuidString:
"12345678-B644-4520-8F0C-720EAF059935")
let proximityUUIDB = UUID(uuidString:
"E2C56DB5-DFFB-48D2-B060-D0F5A71096E0")
let beaconRegionA = CLBeaconRegion(
proximityUUID: proximityUUIDB!,
major: 0x0001,
minor: 0x0004,
identifier: "locationA 49398")
let beaconRegionB = CLBeaconRegion(
proximityUUID: proximityUUIDB!,
major: 0x0001,
minor: 0x0002,
identifier: "locationB 49267")
let beaconRegionC = CLBeaconRegion(
proximityUUID: proximityUUIDB!,
major: 0x0001,
minor: 0x0005,
identifier: "locationC 49141")
let beaconRegionD = CLBeaconRegion(
proximityUUID: proximityUUIDA!,
major: 0x0001,
minor: 0x0002,
identifier: "locationD DSDTECH")
let beaconRegionE = CLBeaconRegion(
proximityUUID: proximityUUIDB!,
major: 0x0001,
minor: 0x0001,
identifier: "locationE 33803")
self.locationManager?.startMonitoring(for: beaconRegionA)
self.locationManager?.startMonitoring(for: beaconRegionB)
self.locationManager?.startMonitoring(for: beaconRegionC)
self.locationManager?.startMonitoring(for: beaconRegionD)
self.locationManager?.startMonitoring(for: beaconRegionE)
print("\(String(describing: self.locationManager?.monitoredRegions)) + monitoredRegions")
}
}
This happens when their state gets determined:
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
if region is CLBeaconRegion {
print("determined state of beacon for region - \(region)")
// Start ranging only if the feature is available.
if CLLocationManager.isRangingAvailable() {
print("determined state of beacon and started ranging")
locationManager?.startRangingBeacons(in: region as! CLBeaconRegion)
// Store the beacon so that ranging can be stopped on demand.
beaconsToRange.append(region as! CLBeaconRegion)
}
}
}
console output:
determined state of beacon for region - CLBeaconRegion (identifier:'locationA 49398', uuid:E2C56DB5-DFFB-48D2-B060-D0F5A71096E0, major:1, minor:4)
determined state of beacon for region - CLBeaconRegion (identifier:'locationB 49267', uuid:E2C56DB5-DFFB-48D2-B060-D0F5A71096E0, major:1, minor:2)
determined state of beacon for region - CLBeaconRegion (identifier:'locationC 49141', uuid:E2C56DB5-DFFB-48D2-B060-D0F5A71096E0, major:1, minor:5)
determined state of beacon for region - CLBeaconRegion (identifier:'locationE 33803', uuid:E2C56DB5-DFFB-48D2-B060-D0F5A71096E0, major:1, minor:1)
determined state of beacon for region - CLBeaconRegion (identifier:'locationE 33803', uuid:E2C56DB5-DFFB-48D2-B060-D0F5A71096E0, major:1, minor:1)
You can see the last two beacons are the same, but it shouldn't be determining the state twice for one beacon, which is why I think the signals are being confused maybe for the one I am missing locationD DSDTECH and locationE 33803.
UPDATE
I changed the major/minor values (which conflicted with another beacons...but not really because the UUID's were different...so it shouldn't have mattered) and now the beacon gets recognized during didDetermineState...but I don't receive any info from it during ranging. I can see in the logs that it went through the locationManager?.startRangingBeacons(in: region as! CLBeaconRegion) function`...so it I should be receiving info (UUID/major/minor/identifier/anything) from it.
Multiple beacons with same UUID, major and minor will behave like as one region.
I think you missing the status. didDetermineState is called when ever state of any region changes (did exit, or did enter) or if you explicitly call requestStateForRegion for that region. Two states of one beacon in your logs, I think one is for status enter and other is for status exit.
In didDetermineState check region state and only start raging if region state is CLRegionStateInside
if state == CLRegionStateInside {
locationManager?.startRangingBeacons(in: region as! CLBeaconRegion)
beaconsToRange.append(region as! CLBeaconRegion)
}
If you are already in the region didDetermineState won't be called unless you exit the region and enter again. To overcome this you should call requestStateForRegion for each region like this.
self.locationManager?.startMonitoring(for: beaconRegionA)
self.locationManager?.requestState(for: beaconRegionA)
So after figuring out the didDetermineState, I took my iBeacon and plugged it in closer to me, and it started receiving info - so it is just a crappy beacon :)

How to detect iBeacons without know UUID,Any Possible to get core bluetooth or Some other way

Is it possible to detect iBeacons without knowing their UUID?
Is there any way to use Core Bluetooth or some other method?
You must know at least the UUID you are looking for in order to create a CLBeaconRegion. There is no way on iOS to scan for "all beacons".
iBeacons are specifically obscured from Core Bluetooth discovery.
While you cannot detect beacons on iOS without specifying the ProximityUUID up front, you can set up ranging to look for a large number of ProximityUUIDs -- I have successfully ranged for 100 of them at the same time (although 1000 crashes my app.)
By using an online beacon database, you can find a list of UUIDs known to be close to you. This won't detect every beacon for sure, but it will allow you to detect many that are around you without having to build the UUIDs into your app.
Here's an example using the NingoSDK to get the 100 nearest ProximityUUIDs to your location and register them for ranging.
let locationManager = CLLocationManager()
// Get up to 100 beacon ProximityUUIDs within 1km from our current location, so we can use these for beacon ranging
let queryClient = QueryBeaconClient(authToken: Settings().getSetting(key: Settings.ningoReadonlyApiTokenKey)!)
queryClient.queryFirstIdentifiers(latitude: latitude, longitude: longitude, radiusMeters: 1000, limit: 100) { (proximityUUIDStrings, errorCode, errorDetail) in
if let proximityUUIDStrings = proximityUUIDStrings {
NSLog("There are now \(proximityUUIDStrings.count) nearby beacon uuids")
if proximityUUIDStrings.count > 0 {
for region in locationManager.rangedRegions {
locationManager.stopRangingBeacons(in: region as! CLBeaconRegion)
}
for uuidString in proximityUUIDStrings {
let region = CLBeaconRegion(proximityUUID: UUID(uuidString: uuidString)!, identifier: uuidString)
locationManager.startRangingBeacons(in: region)
}
BeaconTracker.shared.updateTransientUuids(uuids: proximityUUIDStrings)
}
}
}

performseguewithidentifier with iBeacons

im trying to build a demo app using Estimote Beacons. i want the app to open e specific viewcontroller when the user is near a beacon. im using performseguewithidentifier but when the app starts is opens only the first viewcontroller representing the first beacon which is in the range and it doesnt open the other ones when i go near the other beacons. it somehow just stops ranging for other beacons.
below is the code im using to range for beacons:
func beaconManager(manager: AnyObject, didRangeBeacons beacons: [CLBeacon],
inRegion region: CLBeaconRegion) {
let knownBeacons = beacons.filter{ $0.proximity != CLProximity.Unknown}
if (knownBeacons.count > 0) {
let closestBeacon = knownBeacons [0] as CLBeacon
if(closestBeacon.minor.integerValue==50557){
performSegueWithIdentifier("VC1", sender: nil)
}
else if(closestBeacon.minor.integerValue==37890){
performSegueWithIdentifier("VC2", sender: nil)
}
else if(closestBeacon.minor.integerValue==18976){
performSegueWithIdentifier("VC3", sender: nil)
}
else {
self.view.backgroundColor = UIColor.brownColor()
}
I haven't used Estimote's custom library, but I assume it's similar to the location manager's.
In the Core Location Manager, if your app is in the background you get an entered region notification when you first enter a new beacon region, and then you only get ranging information for a few seconds.
If you've set up your region with a unique UUID and Major ID but no minor ID, then all beacons with that UUID and Major ID are considered part of the same region and you won't reliably get ranging notifications as the beacons with different minor IDs become the closest beacon.
If you want to handle multiple beacons in range at the same time and distinguish between them you'll need to create separate beacon regions for each beacon's UUID, Major ID and minor ID.
I don't know if that's the issue you're facing, but it could be.

Resources