How to get iBeacon CLBeaconRegion identifier (not uuid)? - ios

It's pretty frustrating to not being able to retrieve identifier from CLBeaconRegion. Here's a simplified example:
let beaconRegion = CLBeaconRegion(uuid: UUID(uuidString: "E2C56DB5-DFFB-48D2-B060-D0F5A71096E0")!, major: 111, minor: 222, identifier: "NewBeacon")
locationManager?.startMonitoring(for: beaconRegion)
locationManager?.startRangingBeacons(in: beaconRegion)
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
if let beacon = beacons.first {
print(beacon.identifier) //that
}
}
Is there a way to get "NewBeacon" identifier?

The identifier is associated with the region, you can simply access region.identifier

Related

CoreLocation Non-iBeacon Bluetooth device scan

I want to find Bluetooth devices and get RSSI values using certain period time. I can scan iBeacons. But I also want to find the other Bluetooth devices (like an iPhone device). How can I scan for all devices using CoreLocation?
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways {
if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
if CLLocationManager.isRangingAvailable() {
startScanning()
}
}
}
}
func startScanning() {
let uuid = UUID(uuidString: "XXXXX")!
let beaconRegion = CLBeaconRegion(proximityUUID: uuid, major: 0, minor: 0, identifier: "XXXXX")
locationManager.startMonitoring(for: beaconRegion)
locationManager.startRangingBeacons(in: beaconRegion)
}
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
extendBackgroundRunningTime()
if beacons.count > 0 {
print(beacons)
updateDistance(beacons[0].proximity)
} else {
updateDistance(.unknown)
}
}
You Cannot scan Bluetooth device with this method.You can only scan bluetooth device with Core Bluetooth Frame work.
Go through the below tutorial for bluetooth.
Press here for link

CLLocationManager not monitoring regions

I am perplexed...I had this working today and now I don't know what is going on. It isn't my iBeacon because I can locate it with the Locate iOS app. I am creating my own location manager, not sure if you would call it a subclass exactly because I am subclassing NSObject. Here it is:
//
// LocationManager.swift
// onebeacon
//
// Created by Eamon White on 2/24/18.
// Copyright © 2018 EamonWhite. All rights reserved.
//
import Foundation
import CoreLocation
protocol LocationManagerDelegate: class {
func locationManagerDidUpdateLocation(_ locationManager: LocationManager, location: CLLocation)
func locationManagerDidUpdateHeading(_ locationManager: LocationManager, heading: CLHeading, accuracy: CLLocationDirection)
func locationManagerDidEnterRegion(_ locationManager: LocationManager, didEnterRegion region: CLRegion)
func locationManagerDidExitRegion(_ locationManager: LocationManager, didExitRegion region: CLRegion)
func locationManagerDidDetermineState(_ locationManager: LocationManager, didDetermineState state: CLRegionState, region: CLRegion)
func locationManagerDidRangeBeacons(_ locationManager: LocationManager, beacons: [CLBeacon], region: CLBeaconRegion)
}
class LocationManager: NSObject, CLLocationManagerDelegate {
private var locationManager: CLLocationManager!
weak var delegate: LocationManagerDelegate?
var beaconsToRange: [CLBeaconRegion]
var currentLocation: CLLocation!
override init() {
self.beaconsToRange = []
super.init()
self.locationManager = CLLocationManager()
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
self.locationManager.distanceFilter = kCLDistanceFilterNone
self.locationManager.headingFilter = kCLHeadingFilterNone
self.locationManager.pausesLocationUpdatesAutomatically = false
self.locationManager.delegate = self
self.enableLocationServices()
}
func enableLocationServices() {
self.checkStatus(status: CLLocationManager.authorizationStatus())
}
func checkStatus(status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
// Request when-in-use authorization initially
locationManager.requestAlwaysAuthorization()
break
case .restricted, .denied:
// Disable location features
print("send an alert that the app will not function")
break
case .authorizedWhenInUse:
locationManager.requestAlwaysAuthorization()
// Enable basic location features
break
case .authorizedAlways:
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()
self.monitorBeacons()
// Enable any of your app's location features
break
}
}
func monitorBeacons() {
print("monitorBeacons()")
if CLLocationManager.isMonitoringAvailable(for:
CLBeaconRegion.self) {
print("monitorBeacons().monitoringIsAvailable")
// Match all beacons with the specified UUID
let proximityUUID = UUID(uuidString:
"12345678-B644-4520-8F0C-720EAF059935")
let beaconRegion = CLBeaconRegion(
proximityUUID: proximityUUID!,
major: 0x0001,
minor: 0x0002,
identifier: "iBeacon")
beaconRegion.notifyEntryStateOnDisplay = true;
self.locationManager?.startMonitoring(for: beaconRegion)
print("\(String(describing: self.locationManager?.monitoredRegions)) + monitoredRegions")
}
}
//MARK: - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
self.delegate?.locationManagerDidUpdateLocation(self, location: location)
}
self.currentLocation = manager.location
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
self.delegate?.locationManagerDidUpdateHeading(self, heading: newHeading, accuracy: newHeading.headingAccuracy)
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
if region is CLBeaconRegion {
// Start ranging only if the feature is available.
if CLLocationManager.isRangingAvailable() {
locationManager?.startRangingBeacons(in: region as! CLBeaconRegion)
// Store the beacon so that ranging can be stopped on demand.
beaconsToRange.append(region as! CLBeaconRegion)
}
}
self.delegate?.locationManagerDidEnterRegion(self, didEnterRegion: region)
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
self.delegate?.locationManagerDidExitRegion(self, didExitRegion: region)
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
if region is CLBeaconRegion {
print("determined state of beacon")
// 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)
}
}
self.delegate?.locationManagerDidDetermineState(self, didDetermineState: state, region: region)
}
func locationManager(_ manager: CLLocationManager,
didRangeBeacons beacons: [CLBeacon],
in region: CLBeaconRegion) {
self.delegate?.locationManagerDidRangeBeacons(self, beacons: beacons, region: region)
}
func locationManagerShouldDisplayHeadingCalibration(_ manager: CLLocationManager) -> Bool {
return true
}
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
self.checkStatus(status: status)
}
}
In my ViewController I use it in a very straight forward fashion like this (at the top: delegate methods...somewhat inconsequential for the problem, at the bottom: instantiation):
import UIKit
import SceneKit
import ARKit
import CoreLocation
class ViewController: UIViewController, ARSCNViewDelegate, LocationManagerDelegate {
func locationManagerDidUpdateLocation(_ locationManager: LocationManager, location: CLLocation) {
}
func locationManagerDidUpdateHeading(_ locationManager: LocationManager, heading: CLHeading, accuracy: CLLocationDirection) {
}
func locationManagerDidEnterRegion(_ locationManager: LocationManager, didEnterRegion region: CLRegion) {
}
func locationManagerDidExitRegion(_ locationManager: LocationManager, didExitRegion region: CLRegion) {
}
func locationManagerDidDetermineState(_ locationManager: LocationManager, didDetermineState state: CLRegionState, region: CLRegion) {
}
func locationManagerDidRangeBeacons(_ locationManager: LocationManager, beacons: [CLBeacon], region: CLBeaconRegion) {
print("\(beacons) + beacons for ranging")
if beacons.count > 0 {
let nearestBeacon = beacons.first!
let major = CLBeaconMajorValue(truncating: nearestBeacon.major)
let minor = CLBeaconMinorValue(truncating: nearestBeacon.minor)
print("major: \(major)")
print("minor: \(minor)")
print("accuracy: \(nearestBeacon.accuracy)")
switch nearestBeacon.proximity {
case .immediate:
print("--- immediate ---")
case .near:
print("--- near ---")
case .far:
print("--- far ---")
case .unknown:
print("--- proximity unknown ---")
}
}
}
var sceneView: ARSCNView!
var locationManager: LocationManager!
override func viewDidLoad() {
super.viewDidLoad()
sceneView = ARSCNView()
locationManager = LocationManager()
locationManager.delegate = self
...
My console output is:
2018-02-24 20:40:30.927542-0500 onebeacon[1275:423523] [DYMTLInitPlatform] platform initialization successful
2018-02-24 20:40:32.799470-0500 onebeacon[1275:423484] Metal GPU Frame Capture Enabled
2018-02-24 20:40:32.801237-0500 onebeacon[1275:423484] Metal API Validation Enabled
monitorBeacons()
monitorBeacons().monitoringIsAvailable
Optional(Set([CLBeaconRegion (identifier:'iBeacon', uuid:12345678-B644-4520-8F0C-720EAF059935, major:1, minor:2)])) + monitoredRegions
All of the iBeacon details are correct, there is no way they could have changed from earlier today as it has been plugged in this whole time and not accessed. The problem summarized: it appears to add the region to the "regions-to-be-monitored" list, but the monitoring never seems to start because I get no console messages relaying the iBeacon information.
UPDATE
I will leave the answer I provided as it might be part of it (maybe not)...but now it seems to be starting twice:
2018-02-24 21:35:13.341162-0500 onebeacon[1345:444027] [DYMTLInitPlatform] platform initialization successful
2018-02-24 21:35:16.504017-0500 onebeacon[1345:443977] Metal GPU Frame Capture Enabled
2018-02-24 21:35:16.505384-0500 onebeacon[1345:443977] Metal API Validation Enabled
monitorBeacons()
monitorBeacons().monitoringIsAvailable
Optional(Set([CLBeaconRegion (identifier:'iBeacon', uuid:12345678-B644-4520-8F0C-720EAF059935, major:1, minor:2)])) + monitoredRegions
2018-02-24 21:35:16.747004-0500 onebeacon[1345:443977] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2018-02-24 21:35:16.747969-0500 onebeacon[1345:443977] [MC] Reading from public effective user settings.
monitorBeacons()
monitorBeacons().monitoringIsAvailable
Optional(Set([CLBeaconRegion (identifier:'iBeacon', uuid:12345678-B644-4520-8F0C-720EAF059935, major:1, minor:2)])) + monitoredRegions
As you can see the monitorBeacons()... lines happen twice, I checked to make sure that there is no other instantiation of LocationManager and there isn't.
UPDATE
I narrowed it down...the problem seems to be that the didDetermineState function is not firing initially, I have to walk out of range (or close to it) from the beacon...and then walk back and the didDetermineState method fires, does anyone know why it isn't firing when I am starting in the radius of the beacon?
UPDATE
It appears that my phone is recognizing that it is in a region because when I walk out of the region, the didExitRegion method fires, and then the didDetermineState method...odd because the state should already be determined if the didExitRegion method is firing:
2018-02-24 23:01:09.650445-0500 onebeacon[422:33762] [App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction
2018-02-24 23:01:09.651978-0500 onebeacon[422:33762] [App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction
2018-02-24 23:01:15.007844-0500 onebeacon[422:33762] [App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction
2018-02-24 23:01:15.007893-0500 onebeacon[422:33762] [App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction
2018-02-24 23:02:00.002451-0500 onebeacon[422:33762] Status bar could not find cached time string image. Rendering in-process.
...(put in for easier reading)...
did exit region --- CLBeaconRegion (identifier:'iBeacon', uuid:12345678-B644-4520-8F0C-720EAF059935, major:1, minor:2)
determined state of beacon
determined state of beacon and started ranging
[] + beacons for ranging
[] + beacons for ranging
[] + beacons for ranging
[] + beacons for ranging
[] + beacons for ranging
[] + beacons for ranging
[] + beacons for ranging
What is the pre-commit handler warning? Are those relevant?
My didDetermineState function stopped working on initial load of the app. If I walk outside the range of the beacon, and back into range - the didDetermineState method fires (along with enter/exit region methods). I purchased another iBeacon...and it works fine...also, curiously, when I use both beacons together, both beacons get detected on initial load by didDetermineState. I am not sure why didDetermineState stopped working for the one beacon...when being used in isolation.

Display "Cannot find iBeacon" message

My question is very simple. I would like to display an error message i.e. "Cannot find iBeacon" if iBeacon monitoring fails, after calling startSearchingForSessions via a button press after being called in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager = CLLocationManager()
if self.locationManager.responds(to: #selector(CLLocationManager.requestWhenInUseAuthorization)) {
self.locationManager.requestWhenInUseAuthorization()
}
self.locationManager.delegate = self
self.locationManager.pausesLocationUpdatesAutomatically = false
let uuid = UUID(uuidString: "869A6E2E-AE14-4CF5-8313-8D6976058A7A")
self.beaconRegion = CLBeaconRegion(proximityUUID: uuid!, identifier: "com.dejordan.myapp"
startSearchingForSessions()
}
func startSearchingForSessions() {
// Start looking for the beacons with that UUID and Identifier.
self.locationManager.startMonitoring(for: self.beaconRegion)
self.locationManager.startRangingBeacons(in: self.beaconRegion)
self.locationManager.startUpdatingLocation()
}
And handling the found beacons thusly:
// Required by the Location Manager.
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
self.locationManager.startRangingBeacons(in: self.beaconRegion)
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
if state == CLRegionState.outside {
print("Cannot Find Beacon")
}
}
// Required by the Location Manager.
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
self.locationManager.stopRangingBeacons(in: self.beaconRegion)
}
// This is called if any beacons are found.
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
var result = Array<CLBeacon>()
for beacon in beacons {
result.append(beacon)
}
foundBeacons = result
// If we found any, we need to see
// what class they belong to based on information
// from Parse.
self.identifyFoundBeacons()
// We can stop looking for beacons now.
self.locationManager.stopMonitoring(for: self.beaconRegion)
self.locationManager.stopRangingBeacons(in: self.beaconRegion)
self.locationManager.stopUpdatingLocation()
}
I have implemented the delegate error methods in an attempt to find where this occurs but thus far in navigating the mounds of documentation on iBeacon I have come up fruitless.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Location manager failed: \(error.localizedDescription)")
}
func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
print("Failed monitoring region: \(error.localizedDescription)")
}
Thank you!
If you simply want to know when beacons are not detected (vs. when there was a low-level failure to look for beacons), then simply use the following delegate method:
public func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
if state == CLRegionState.outside {
print("Cannot find beacon")
}
}
Interestingly enough, didRangeBeacons in the delegate method
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion)
gets called with an empty array of [CLBeacon]s, wherein I can use the beacons array size to determine whether or not any beacons were found.
Not what I expected, but this has solved my problem!

Not able to detect Kontakt.io beacons in my iOS app

I had did beacon searching code as per Kontakt SDK Sample code as below. But I am getting beacon count always 0, while I am having 11 beacons near by my iPhone. Can any body help me over this?
I have initialise KTKBeaconManager in viewDidLoad method and then create region object and stopped any previous ranging service and then started new monitoring and ranging services.
And all time it calls didRangeBeacons with beacons count = 0. Not sure what exactly the issue. Its same code from their example code.
import UIKit
import KontaktSDK
class ViewController: UIViewController {
var beaconManager: KTKBeaconManager!
#IBOutlet var statusLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Initiate Beacon Manager
beaconManager = KTKBeaconManager(delegate: self)
beaconManager.requestLocationAlwaysAuthorization()
// Region
let proximityUUID = NSUUID(uuidString: "f7826da6-4fa2-4e98-8024-bc5b71e0893e")
let region = KTKBeaconRegion(proximityUUID: proximityUUID! as UUID, identifier: "com.weenggs.KontaktDemo")
// Region Properties
region.notifyEntryStateOnDisplay = true
beaconManager.stopMonitoringForAllRegions()
// Start Ranging
beaconManager.startMonitoring(for: region)
beaconManager.startRangingBeacons(in: region)
beaconManager.requestState(for: region)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: KTKBeaconManagerDelegate {
func beaconManager(_ manager: KTKBeaconManager, didDetermineState state: CLRegionState, for region: KTKBeaconRegion) {
print("Did determine state \"\(state.rawValue)\" for region: \(region)")
statusLabel.text = "Did determine state \"\(state.rawValue)\" for region: \(region)"
}
func beaconManager(_ manager: KTKBeaconManager, didChangeLocationAuthorizationStatus status: CLAuthorizationStatus) {
print("Did change location authorization status to: \(status.rawValue)")
statusLabel.text = "Did change location authorization status to: \(status.rawValue)"
if status == .authorizedAlways{
// Region
let proximityUUID = NSUUID(uuidString: "f7826da6-4fa2-4e98-8024-bc5b71e0893e")
let region = KTKBeaconRegion(proximityUUID: proximityUUID! as UUID, identifier: "com.weenggs.KontaktDemo")
// Region Properties
region.notifyEntryStateOnDisplay = true
beaconManager.startMonitoring(for: region)
beaconManager.startRangingBeacons(in: region)
beaconManager.requestState(for: region)
}
}
func beaconManager(_ manager: KTKBeaconManager, monitoringDidFailFor region: KTKBeaconRegion?, withError error: Error?) {
print("Monitoring did fail for region: \(region)")
print("Error: \(error)")
statusLabel.text = "Monitoring did fail for region: \(region)"
}
func beaconManager(_ manager: KTKBeaconManager, didStartMonitoringFor region: KTKBeaconRegion) {
print("Did start monitoring for region: \(region)")
statusLabel.text = "Did start monitoring for region: \(region)"
}
func beaconManager(_ manager: KTKBeaconManager, didEnter region: KTKBeaconRegion) {
print("Did enter region: \(region)")
statusLabel.text = "Did enter region: \(region)"
}
func beaconManager(_ manager: KTKBeaconManager, didExitRegion region: KTKBeaconRegion) {
print("Did exit region \(region)")
statusLabel.text = "Did exit region \(region)"
}
func beaconManager(_ manager: KTKBeaconManager, didRangeBeacons beacons: [CLBeacon], in region: KTKBeaconRegion) {
print("Did ranged \"\(beacons.count)\" beacons inside region: \(region)")
statusLabel.text = "Did ranged \"\(beacons.count)\" beacons inside region: \(region)"
if let closestBeacon = beacons.sorted(by: { $0.0.accuracy < $0.1.accuracy }).first , closestBeacon.accuracy > 0 {
print("Closest Beacon is M: \(closestBeacon.major), m: \(closestBeacon.minor) ~ \(closestBeacon.accuracy) meters away.")
statusLabel.text = "\(statusLabel.text) Closest Beacon is M: \(closestBeacon.major), m: \(closestBeacon.minor) ~ \(closestBeacon.accuracy) meters away."
}
}
}
I reckon the common issue is that you forgot to set
Kontakt.setAPIKey("yourSuperSecretAPIKey")
and either one of those two permissions
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
If it's not the case then your beacons' batteries could be drained out.
Finally I was able to detect beacons using CBPeripheral class and identify uniquely based on received UUID with instance id( last 12 characters are instance id which are unique)

custome ios app cannot find my nrf beacons

I have some beacons with this uuid:
0112233445566778899aabbccddeeff0
and major = 1 but their minor are different.
this is a part of firmware code which shows these numbers:
#define APP_MAJOR_VALUE 0x01, 0x02 #define APP_MINOR_VALUE 0x03, 0x04
#define APP_BEACON_UUID 0x01, 0x12, 0x23, 0x34, \
0x45, 0x56, 0x67, 0x78, \
0x89, 0x9a, 0xab, 0xbc, \
0xcd, 0xde, 0xef, 0xf0
static uint8_t m_beacon_info[APP_BEACON_INFO_LENGTH] =
{
APP_DEVICE_TYPE,
APP_ADV_DATA_LENGTH,
APP_BEACON_UUID,
APP_MAJOR_VALUE,
APP_MINOR_VALUE,
APP_MEASURED_RSSI
};
and this is my swift code:
import UIKit
import CoreLocation
import CoreBluetooth
class HomeViewController: UIViewController, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
var managerBLE: CBCentralManager?
override func viewDidLoad() {
super.viewDidLoad()
managerBLE = CBCentralManager(delegate: nil, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey: true])
locationManager = CLLocationManager()
locationManager.delegate = self
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
locationManager.requestWhenInUseAuthorization()
}
startScanning()
}
func startScanning() {
let beaconRegion = CLBeaconRegion(proximityUUID: UUID(uuidString: "your UUID")!, major: 1, identifier: "MyBeacon")
locationManager.startRangingBeacons(in: beaconRegion)
}
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
if beacons.count > 0 {
for beacon in beacons {
updateDistance(beacon.proximity)
if beacon.proximity == .near {
// run your code
}else if beacon.proximity == .far {
// run your code
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
but when i instaall my app on my iphone basically nothing happens. I have no idea what i am doing wrong?
Your code needs to be debugged. Unfortunately it's tough for us to do because we don't have beacon. Try printing to the logs when ever you are able to connect to a beacon. It's a good starting place for debugging.
Make sure your beacon's have battery and that they are in range.
A few issues:
This line: CLLocationManager.authorizationStatus() == .authorizedWhenInUse should be CLLocationManager.authorizationStatus() != .authorizedWhenInUse
You need to place your UUID including dashes in place of the string "your UUID" in this line CLBeaconRegion(proximityUUID: UUID(uuidString: "your UUID")!,
There is no need to use CBCentralManager at all.
EDIT: You should also try an off-the-shelf beacon detector app like Locate (entering your UUID with dashes to configure it to detect your beacon) and verify it sees it. If it does not see, it, it may be an issue with your hardware beacon, or perhaps the UUID is not what you think it is.
SWIFT 3:
First of all you should add in the .Plist file add the key/string NSLocationAlwaysUsageDescriptionwith appropriate string
In your Object add the CLLocationManagerDelegate
Add the CLLocationManagerDelegate delegate methods in this example i will just add the didRangeBeacons method
func locationManager(_ manager: CLLocationManager, didRangeBeacons
beacons: [CLBeacon], in region: CLBeaconRegion) {
print(beacons) }
Create and initialise the locationManager
let locationManager : CLLocationManager = CLLocationManager()
Create the CLBeaconRegion
let beaconRegion : CLBeaconRegion = CLBeaconRegion(
proximityUUID: NSUUID.init(uuidString:"****-****-****-****-******") as! UUID,
identifier: "my beacon")
Add the delegate to your Object locationManager.delegate = self
Request the Location authorization from the user with
locationManager.requestAlwaysAuthorization()
Now let's start the Range
locationManager.startRangingBeacons(in: beaconRegion)
This will automatically call the delegate method
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
print(beacons)
}

Resources