UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to detect iBeacons

Swift version: 5.6

Paul Hudson    @twostraws   

Detecting iBeacons requires a number of steps, but before we can start writing any code we first need to add some privacy descriptions to your Info.plist file. These are shown to users when you request location access, and it’s your chance to explain to users why you need location access.

The two keys we need to add are “Privacy - Location Always and When In Use Usage Description” and “Privacy - Location When In Use Usage Description”. So, please go to your Info.plist now, and give them both a string describing why you want access.

With that done, we can start to scan for beacons. Open your class in Xcode (it could be a view controller, but it doesn't have to be), add an import for CoreLocation to the top, then tell Swift that your class conforms to the CLLocationManagerDelegate protocol so that you can start to receive location updates.

iBeacon tracking is done using the CLLocationManager class, which is also responsible for requesting location permission from users. You need to create a property for this in your class so that you can store the active location manager, so add this:

var locationManager: CLLocationManager!

If you're using a view controller, you'll probably want to initialize this property in viewDidLoad(), like this:

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.requestAlwaysAuthorization()
}

If you're using another type of class, you should amend that appropriately.

Once you request permission to use your user's location, they'll see an alert with the message you wrote earlier. When they make a choice you'll get a delegate callback called didChangeAuthorization, at which point you can check whether they are authorized you or not:

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if status == .authorizedAlways {
        if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
            if CLLocationManager.isRangingAvailable() {
                startScanning()
            }
        }
    }
}

Don't worry, we haven't written the startScanning() method yet.

Once you've been authorized to scan for iBeacons, you can create CLBeaconRegion objects and pass them to the location manager. Each CLBeaconRegion is uniquely identified by a long number (it's UUID), and optionally also major and minor numbers. As well as monitoring for a beacon's existence, we're also going to ask iOS to range the beacon for us – i.e., tell us how close it thinks we are.

Here's the code:

func startScanning() {
    let uuid = UUID(uuidString: "5A4BCFCE-174E-4BAC-A814-092E77F6B7E5")!
    let beaconRegion = CLBeaconRegion(proximityUUID: uuid, major: 123, minor: 456, identifier: "MyBeacon")

    locationManager.startMonitoring(for: beaconRegion)
    locationManager.startRangingBeacons(in: beaconRegion)
}

Once you're ranging for beacons, you'll get a delegate callback called didRangeBeacons every second or so, at which point you can read a beacon's distance using its proximity value and take appropriate action.

For example, we can make our view change color depending on how far away an iBeacon is with this code:

func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
    if beacons.count > 0 {
        updateDistance(beacons[0].proximity)
    } else {
        updateDistance(.unknown)
    }
}

func updateDistance(_ distance: CLProximity) {
    UIView.animate(withDuration: 0.8) {
        switch distance {
        case .unknown:
            self.view.backgroundColor = UIColor.gray

        case .far:
            self.view.backgroundColor = UIColor.blue

        case .near:
            self.view.backgroundColor = UIColor.orange

        case .immediate:
            self.view.backgroundColor = UIColor.red
        }
    }
}

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 7.0 – see Hacking with Swift tutorial 22

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.3/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.