NEW: Learn SwiftUI with my free YouTube video series! >>

How to detect iBeacons

Swift version: 5.0

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() {

    locationManager = CLLocationManager()
    locationManager.delegate = self

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() {

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 {
    } else {

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

        case .far:
            self.view.backgroundColor =

        case .near:
            self.view.backgroundColor =

        case .immediate:
            self.view.backgroundColor =

SPONSOR Meet the new Instabug – more than just bug reporting! We help you build better apps and minimize your debugging time. With each bug report, we automatically capture details like network requests, repro steps, and session details. Get real-time crash reports with stack trace details and session data to help you catch and fix issues easily. And with our customizable in-app surveys, you’ll gather insightful user feedback and much more. Instabug is the fastest and easiest way to release with confidence. Start your free trial now! Start your free trial now!

Available from iOS 7.0 – see Hacking with Swift tutorial 22

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

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

Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.8/5

Click here to visit the Hacking with Swift store >>