iOS iBeacon app tutorial with Swift 2

iOS iBeacon app tutorial

  • What is iBeacon?
  • How iBeacon works?
  • Understanding Beacon Ranging
  • iBeacon settings
  • Code example & explanation for iOS iBeacon app tutorial divided into 8 parts:
    1. Create Project
    2. Create User Interface
    3. Create iBeacon file
    4. Check location service Authorization status
    5. iBeacon Region Monitoring
    6. iBeacon Distance Monitoring
    7. Check Bluetooth
    8. info.plist

What is iBeacon?

iBeacon is a protocol developed by Apple and introduced at the Apple Worldwide Developers Conference in 2013. Various vendors have since made iBeacon-compatible hardware transmitters – typically called beacons – a class of Bluetooth low energy (LE) devices that broadcast their identifier to nearby portable electronic devices. The technology enables smartphones, tablets and other devices to perform actions when in close proximity to an iBeacon.

iBeacon uses Bluetooth low energy proximity sensing to transmit a universally unique identifier picked up by a compatible app or operating system. The identifier and several bytes sent with it can be used to determine the device’s physical location, track customers, or trigger a location-based action on the device such as a check-in on social media or a push notification.

iBeacon differs from some other location-based technologies as the broadcasting device (beacon) is only a 1-way transmitter to the receiving smartphone or receiving a device, and necessitates a specific app installed on the device to interact with the iBeacons. This ensures that only the installed app (not the iBeacon transmitter) can track users, potentially against their will, as they passively walk around the transmitters.

iBeacon compatible transmitters come in a variety of form factors, including small coin cell devices, USB sticks, and generic Bluetooth 4.0 capable USB dongles.

iOS iBeacon app tutorial

to learn more about iBeacon check this Wikipedia article.

After understating what is iBeacon it would be essential to know how it works, the range of it’s Bluetooth transmitter and setting it provides in order completely understand the code we will be covering very soon for iOS iBeacon app tutorial. If you already know this general stuff for iBeacon and would like to see the code. Please skip these intro parts.

How iBeacon work?

An iBeacon deployment consists of one or more iBeacon devices that transmit their own unique identification number to the local area. Software on a receiving device may then look up the iBeacon and perform various functions, such as notifying the user. Receiving devices can also connect to the iBeacons to retrieve values from iBeacon’s GATT (generic attribute profile) service.

iBeacons do not push notifications to receive devices (other than their own identity). However, the mobile software can use signals received from iBeacons to trigger their own push notifications.

iBeacon Region

Region monitoring

Region monitoring is limited to 20 regions and can function in the background (of the listening device) and has different delegates to notify the listening app (and user) of entry/exit in the region – even if the app is in the background or the phone is locked.

iOS iBeacon app tutorial - iBeacon Region


As opposed to monitoring, which enables users to detect movement in-and-out of a range of the iBeacons, ranging provides a list of iBeacons detected in a given region, along with the estimated distance from the user’s device to each iBeacon.

An iOS device receiving an iBeacon transmission can approximate the distance from the iBeacon. The distance (between transmitting iBeacon and receiving device) is categorized into 3 distinct ranges:

iOS iBeacon app tutorial - iBeacon range

Immediate Within a few centimeters
Near Within a couple of meters
Far Greater than 10 meters away


An iBeacon broadcast has the ability to approximate when a user has entered, exited, or lingered in the region. Depending on a customer’s proximity to a beacon, they are able to receive different levels of interaction at each of these three ranges.

The maximum range of an iBeacon transmission will depend on the location and placement, obstructions in the environment and where the device is being stored (e.g. in a leather handbag or with a thick case). Standard beacons have an approximate range of 70 meters. Long range beacons can reach up to 450 meters.

iBeacon Settings

The frequency of the iBeacon transmission depends on the configuration of the iBeacon and can be altered using device specific methods. Both the rate and the transmit power have an effect on the iBeacon battery life. iBeacons come with predefined settings and several of them can be changed by the developer. Amongst others, the rate and the transmit power can be changed as well as the Major and Minor values.

The Major and Minor values are settings which can be used to connect to specific iBeacons or to work with more than one iBeacon at the same time. Typically, multiple iBeacon deployments at a venue will share the same UUID, and use the major and minor pairs to segment and distinguish subspaces within the venue.

For example, the UUID values of all the iBeacons in a specific store can be set to the same value and the Minor and Major value can be used to identify a specific iBeacon within the store.

iOS iBeacon app tutorial - iBeacon same uuid

iOS iBeacon app tutorial

Step 1 – Create project

Create new Xcode project and select “Single View Application” template. Enter your project name as iOS iBeacon app tutorial or something and set swift as a programming language.

Step 2 – Create User Interface

In this example, we simply display iBeacon details in the label.

In your project go to ‘ViewController.swif ‘file and replace the code that given below

import UIKit
import CoreLocation
import CoreBluetooth

class ViewController: UIViewController,CBPeripheralManagerDelegate {
    @IBOutlet weak var beaconStatus: UILabel!
    let locationManager = CLLocationManager()
    let myBTManager = CBPeripheralManager()
    var lastStage = CLProximity.Unknown
    override func viewDidLoad() {
        // Do any additional setup after loading the view, typically from a nib.
      // Define in iBeacon.swift  

    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

Make sure that you set label height and width properly and set ‘lines’ property to zero.

In the view controller, we just define variables that use in ‘iBeacon.swift’ file.

Due to extension restriction we can not define variable in extension so that we define that variables in our ViewController.

Step 3 – Create iBeacon file

After creating a project add new swift file”iBeacon.swift” to your project folder. Now add the following import code to your iBeacon file.

import UIKit
import CoreLocation

The Core Location framework lets you determine the current location or heading associated with a device. You can also use it to define geographic regions and monitor when the user crosses the boundaries of those regions. In iOS, you can also define a region around a Bluetooth iBeacon.

Create extension for ViewController and add CLLocationManagerDelegate

extension ViewController: CLLocationManagerDelegate {


Now we need to setup our iBeacon.

extension ViewController: CLLocationManagerDelegate {

        func setupBeacon() {

            locationManager.delegate = self
            // Enter Your iBeacon UUID
            let uuid = NSUUID(UUIDString: "bebbf6eb-a2cb-47be-aec5-8bb6a2c8ffda")!
            // Use identifier like your company name or website
            let identifier = "com.alphansotech"
            let Major:CLBeaconMajorValue = 100
            let Minor:CLBeaconMinorValue = 1
            let beaconRegion = CLBeaconRegion(proximityUUID: uuid, major: Major, minor: Minor, identifier: identifier)
            // called delegate when Enter iBeacon Range
            beaconRegion.notifyOnEntry = true
            // called delegate when Exit iBeacon Range
            beaconRegion.notifyOnExit = true
            // Requests permission to use location services
            // Starts monitoring the specified iBeacon Region
            locationManager.pausesLocationUpdatesAutomatically = false

Contact iBeacon Manufacturer for your iBeacon UUID, Major Value, Minor Value etc.

Step 4 – Check Location Service Authorization Status

extension ViewController: CLLocationManagerDelegate {

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        switch status {
        case .AuthorizedAlways:
            // Starts the generation of updates that report the user’s current location.

        case .Restricted:
            // Your app is not authorized to use location services.
            simpleAlert("Permission Error", message: "Need Location Service Permission To Access Beacon")

        case .Denied:
            // The user explicitly denied the use of location services for this app or location services are currently disabled in Settings.
           simpleAlert("Permission Error", message: "Need Location Service Permission To Access Beacon")

            // handle .NotDetermined here
            // The user has not yet made a choice regarding whether this app can use location services.
    func simpleAlert (title:String,message:String) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil))
        self.presentViewController(alertController, animated: true, completion: nil)


SimpleAlert Function is used to display alert in a app.

Step 5 – iBeacon Region Monitoring

extension ViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didStartMonitoringForRegion region: CLRegion) {
        // Tells the delegate that a iBeacon Area is being monitored
    func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {
        // Tells the delegate that the user entered in iBeacon range or area.
        simpleAlert("Welcom", message: "Welcome to our store")
        // This method called because
        // beaconRegion.notifyOnEntry = true
        // in setupBeacon() function

    func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) {
        // Tells the delegate that the user exit the iBeacon range or area.
        simpleAlert("Good Bye", message: "Have a nice day")
        // This method called because
        // beaconRegion.notifyOnExit = true
        // in setupBeacon() function        
    func locationManager(manager: CLLocationManager, didDetermineState state: CLRegionState, forRegion region: CLRegion) {
        switch  state {
        case .Inside:
            //The user is inside the iBeacon range.
            locationManager.startRangingBeaconsInRegion(region as! CLBeaconRegion)

        case .Outside:
            //The user is outside the iBeacon range.
            locationManager.stopRangingBeaconsInRegion(region as! CLBeaconRegion)
        default :
            // it is unknown whether the user is inside or outside of the iBeacon range.

Step 6 – iBeacon Distance Monitoring

extension ViewController: CLLocationManagerDelegate {

func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion)
        // Tells the delegate that one or more beacons are in range.
       let foundBeacons = beacons
        if foundBeacons.count > 0 {
            if let closestBeacon = foundBeacons[0] as? CLBeacon {
                    var proximityMessage: String!
                if lastStage != closestBeacon.proximity {
                    lastStage = closestBeacon.proximity
                    switch  lastStage {
                    case .Immediate:
                        proximityMessage = "Very close"
                        self.view.backgroundColor = UIColor.greenColor()
                    case .Near:
                        proximityMessage = "Near"
                        self.view.backgroundColor = UIColor.grayColor()
                    case .Far:
                        proximityMessage = "Far"
                        self.view.backgroundColor = UIColor.blackColor()
                        proximityMessage = "Where's the beacon?"
                        self.view.backgroundColor = UIColor.redColor()
                    var makeString = "Beacon Details:n"
                    makeString += "UUID = (closestBeacon.proximityUUID.UUIDString)n"
                    makeString += "Identifier = (region.identifier)n"
                    makeString += "Major Value = (closestBeacon.major.intValue)n"
                    makeString += "Minor Value = (closestBeacon.minor.intValue)n"
                    makeString += "Distance From iBeacon = (proximityMessage)"

                    self.beaconStatus.text = makeString


It’s a good idea to save last stage of user distance, because this method called frequently.

Step 7 – Check Bluetooth

Add the following code to ‘ViewController.swift’ file

func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
        if peripheral.state == CBPeripheralManagerState.PoweredOff {
            simpleAlert("Beacon", message: "Turn On Your Device Bluetooh")

Make sure that your ViewController extend the ‘CBPeripheralManagerDelegate’.

Step 8 – info.plist : the final step for iOS iBeacon app tutorial!

In your project find the ‘info.plist’ file and right click on it. go to ‘Open As’ menu and select ‘Source Code’. Now find the ‘<dict>‘ and add the following code after that.

<string>Need permission to spot iBeacons</string>

Add this property, because iOS 8 and later this property is required.

Below is the link to download the complete Xcode project for iOS iBeacon app tutorial


Xcode Project


Do you like our iOS iBeacon app tutorial? Need to develop iBeacon application? Contact us for iBeacon app development today.

Post by Milan Sanathara

I am iOS Application Developer with an aspiration of learning new technology and creating a bright future in Information Technology.

6 Responses to iOS iBeacon app tutorial with Swift 2

  1. Pingback: iOS iBeacon app tutorial with Swift 2 | Dinesh Ram Kali.

  2. Pingback: iOS iBeacon app tutorial with Swift 2 | Swift Advanced

  3. I’ve been surfing on-line more than 3 hours
    today, yet I never found any attention-grabbing article like
    yours. It is beautiful worth sufficient for me.

    In my view, if all web owners and bloggers made good content material as you did, the
    internet will likely be a lot more useful than ever before.

Leave a Reply

Your email address will not be published. Required fields are marked *