{"id":2838,"date":"2017-08-16T07:05:46","date_gmt":"2017-08-16T07:05:46","guid":{"rendered":"https:\/\/intelligentbee.com\/blog\/?p=2838"},"modified":"2024-06-30T09:06:51","modified_gmt":"2024-06-30T09:06:51","slug":"introduction-ibeacons-ios","status":"publish","type":"post","link":"https:\/\/intelligentbee.com\/blog\/introduction-ibeacons-ios\/","title":{"rendered":"Introduction to iBeacons on iOS"},"content":{"rendered":"<p>Hello, I got my hands on some interesting devices from <b>Estimote<\/b> called <b>iBeacons<\/b> which they are used for sending signals to the users (<b>iOS\/ Android<\/b>) phone using <b>Bluetooth<\/b>.<\/p>\n<p>What I\u2019m going to do next is to build an <b>iOS app<\/b>\u00a0using these devices which changes the background color accordingly to the nearest one of these 3 beacons.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-2839\" src=\"https:\/\/intelligentbee.com\/blog\/wp-content\/uploads\/2017\/08\/Ibeacons-300x225.jpg\" alt=\"\" width=\"1024\" height=\"768\" srcset=\"https:\/\/intelligentbee.com\/blog\/wp-content\/uploads\/2017\/08\/Ibeacons-300x225.jpg 300w, https:\/\/intelligentbee.com\/blog\/wp-content\/uploads\/2017\/08\/Ibeacons-768x576.jpg 768w, https:\/\/intelligentbee.com\/blog\/wp-content\/uploads\/2017\/08\/Ibeacons.jpg 1024w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/p>\n<h2>Introduction to iBeacons on iOS<\/h2>\n<p>The first thing that you have to do after you create a new project from <strong>XCode<\/strong>\u00a0of Single View Application type is to install <strong>\u2018EstimoteSDK\u2019<\/strong> using Cocoa pods. If you don\u2019t have <strong>Cocoapods<\/strong> installed on your Mac please do it by following the instructions they offer.<\/p>\n<p>From the terminal window \u00a0use &#8220;<em>cd<\/em>&#8221; to navigate into your project directory and run &#8220;pod init&#8221;. This will create a podfile in your project directory. Open it and under &#8220;# Pods for\u00a0<em>your project name<\/em>&#8221; add the following line:<\/p>\n<pre class=\"lang:swift decode:true \">pod 'EstimoteSDK'<\/pre>\n<p>Then run <em>&#8220;pod install&#8221;<\/em> command in your terminal. After the installation of the cocoapod \u00a0close the project and open the <em>.workspace<\/em> file and\u00a0create a bridging header.\u00a0Import there the <b>EstimoteSDK<\/b> with the code below.<\/p>\n<pre class=\"lang:swift decode:true \">#import &lt;EstimoteSDK\/EstimoteSDK.h&gt;<\/pre>\n<p>Now let\u2019s continue by creating a <strong>\u2018iBeaconViewController\u2019<\/strong> with a <em>UILabel<\/em> inside of it having full width and height and the text aligned center, after this please create an IBOutlet to it and name it <strong>&#8216;label&#8217;<\/strong>\u00a0. Then set the new created view controller as the root view for the window.<\/p>\n<pre class=\"lang:swift decode:true\"> func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -&gt; Bool {\r\n        \/\/ Override point for customization after application launch.\r\n        \r\n        window?.rootViewController = UIBeaconViewController(nibName: String(describing: UIBeaconViewController.self), bundle: nil)\r\n        \r\n        return true\r\n    }<\/pre>\n<p>The next step is creating the <b style=\"font-size: 1rem;\">\u2018BeaconManager\u2019<\/b>&lt; file, you have it\u2019s content below.<\/p>\n<pre class=\"lang:default decode:true \">import UIKit\r\n\r\nenum MyBeacon: String {\r\n    \r\n    case pink = \"4045\"\r\n    case magenta = \"20372\"\r\n    case yellow = \"22270\"\r\n}\r\n\r\nlet BeaconsUUID: String = \"B9407F30-F5F8-466E-AFF9-25556B57FE6D\"\r\nlet RegionIdentifier: String  = \"IntelligentBee Office\"\r\nlet BeaconsMajorID: UInt16  = 11111\r\n\r\nclass BeaconManager: ESTBeaconManager {\r\n\r\n    static let main : BeaconManager = BeaconManager()\r\n    \r\n}\r\n<\/pre>\n<p>But let\u2019s first explain what is the purpose of each item in this file. So an iBeacon contains the following main properties, an <b>UUID<\/b>, <b>MajorID<\/b>, <b>MinorID<\/b>. All of these properties represents a way for the phone to know which device should listen to.<\/p>\n<p>The <b>MajorID<\/b> is used when having groups of beacons and the <b>MinorID<\/b> is to know each specific device, the minor ids are represented in the <b>MyBeacon<\/b> <b>enum<\/b> among with the <b>beacon color<\/b>. The <b>RegionIdentifier<\/b> represents a way for the app to know what region are the beacons part of and it\u2019s used to differentiate all the regions that are monitored by the app.<\/p>\n<p>Now let\u2019s go back on the <b>UIBeaconViewController<\/b> and start writing some action.<\/p>\n<pre class=\"lang:swift decode:true \">import UIKit\r\n\r\nclass UIBeaconViewController: UIViewController, ESTBeaconManagerDelegate {\r\n    \r\n    \/\/ MARK: - Props\r\n    \r\n    let region = CLBeaconRegion(\r\n        proximityUUID: UUID(uuidString: BeaconsUUID)!,\r\n        major: BeaconsMajorID, identifier: RegionIdentifier)\r\n    \r\n    let colors: [MyBeacon : UIColor] =\r\n        [MyBeacon.pink: UIColor(red: 240\/255.0, green: 183\/255.0, blue: 183\/255.0, alpha: 1),\r\n         MyBeacon.magenta : UIColor(red: 149\/255.0, green: 70\/255.0, blue: 91\/255.0, alpha: 1),\r\n         MyBeacon.yellow : UIColor(red: 251\/255.0, green: 254\/255.0, blue: 53\/255.0, alpha: 1)]\r\n    \r\n    \/\/ MARK: - IBOutlets\r\n    \r\n    @IBOutlet weak var label: UILabel!<\/pre>\n<p>You can guess what <b>region<\/b> does, it defines a location to detect beacons, pretty intuitive. The <b>colors<\/b> is an array which contains the mapping between the <b>minorID<\/b> and the <b>color<\/b> of each beacon.<\/p>\n<pre class=\"lang:swift decode:true\">\/\/ MARK: - UI Utilities\r\n    \r\n    func resetBackgroundColor() {\r\n        self.view.backgroundColor = UIColor.green\r\n    }\r\n    \r\n    \/\/ MARK: - ESTBeaconManagerDelegate - Utilities\r\n    \r\n    func setupBeaconManager() {\r\n        BeaconManager.main.delegate = self\r\n        \r\n        if (BeaconManager.main.isAuthorizedForMonitoring() &amp;&amp; BeaconManager.main.isAuthorizedForRanging()) == false {\r\n            BeaconManager.main.requestAlwaysAuthorization()\r\n        }\r\n    }\r\n    \r\n    func startMonitoring() {\r\n        \r\n        BeaconManager.main.startMonitoring(for: region)\r\n        BeaconManager.main.startRangingBeacons(in: region)\r\n    }\r\n<\/pre>\n<p>The functions above are pretty self describing from their names, one thing I need to describe is <b>Monitoring<\/b> and <b>Ranging<\/b>. The <b>monitoring<\/b> actions are triggered when the phone enters\/ exits a beacons area and the <b>ranging<\/b> is based on the proximity of the beacon.<\/p>\n<pre class=\"lang:swift decode:true \">    \/\/ MARK: - ESTBeaconManagerDelegate\r\n    \r\n    func beaconManager(_ manager: Any, didChange status: CLAuthorizationStatus) {\r\n        \r\n        if status == .authorizedAlways ||\r\n            status == .authorizedWhenInUse {\r\n            startMonitoring()\r\n        }\r\n    }\r\n    \r\n    func beaconManager(_ manager: Any, monitoringDidFailFor region: CLBeaconRegion?, withError error: Error) {\r\n        label.text = \"FAIL \" + (region?.proximityUUID.uuidString)!\r\n    }\r\n    \r\n    func beaconManager(_ manager: Any, didEnter region: CLBeaconRegion) {\r\n        \r\n        label.text = \"Hello beacons from \\(region.identifier)\"\r\n    }\r\n    \r\n    func beaconManager(_ manager: Any, didExitRegion region: CLBeaconRegion) {\r\n        \r\n        label.text = \"Bye bye beacons from \\(region.identifier)\"\r\n    }\r\n    \r\n    func beaconManager(_ manager: Any, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {\r\n        \r\n        let knownBeacons = beacons.filter { (beacon) -&gt; Bool in\r\n            \r\n            return beacon.proximity != CLProximity.unknown\r\n        }\r\n        \r\n        if let firstBeacon = knownBeacons.first,\r\n            let myBeacon = MyBeacon(rawValue:firstBeacon.minor.stringValue)   {\r\n            \r\n            let beaconColor = colors[myBeacon]\r\n            self.view.backgroundColor = beaconColor\r\n        }\r\n        else {\r\n            resetBackgroundColor()\r\n        }\r\n    }\r\n    \r\n    func beaconManager(_ manager: Any, didFailWithError error: Error) {\r\n        label.text = \"DID FAIL WITH ERROR\" + error.localizedDescription\r\n    }\r\n}\r\n<\/pre>\n<p>After the insertion of all the code, the app should run with no errors or warning and should look like this:<\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-2846 size-full\" src=\"https:\/\/intelligentbee.com\/blog\/wp-content\/uploads\/2017\/08\/Image-uploaded-from-iOS-1.jpg\" alt=\"\" width=\"1024\" height=\"768\" srcset=\"https:\/\/intelligentbee.com\/blog\/wp-content\/uploads\/2017\/08\/Image-uploaded-from-iOS-1.jpg 1024w, https:\/\/intelligentbee.com\/blog\/wp-content\/uploads\/2017\/08\/Image-uploaded-from-iOS-1-300x225.jpg 300w, https:\/\/intelligentbee.com\/blog\/wp-content\/uploads\/2017\/08\/Image-uploaded-from-iOS-1-768x576.jpg 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/> <img decoding=\"async\" class=\"aligncenter wp-image-2847 size-full\" src=\"https:\/\/intelligentbee.com\/blog\/wp-content\/uploads\/2017\/08\/Image-uploaded-from-iOS.jpg\" alt=\"\" width=\"1024\" height=\"768\" srcset=\"https:\/\/intelligentbee.com\/blog\/wp-content\/uploads\/2017\/08\/Image-uploaded-from-iOS.jpg 1024w, https:\/\/intelligentbee.com\/blog\/wp-content\/uploads\/2017\/08\/Image-uploaded-from-iOS-300x225.jpg 300w, https:\/\/intelligentbee.com\/blog\/wp-content\/uploads\/2017\/08\/Image-uploaded-from-iOS-768x576.jpg 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/p>\n<p>I hope this is a good introduction for <strong>i<\/strong><strong>Beacons<\/strong> in <b>iOS Mobile App Development<\/b>. If you have any improvements or suggestions please leave a comment below.<\/p>\n<p>You can get the code from here: <a href=\"https:\/\/github.com\/intelligentbee\/iBeaconTest\" target=\"_blank\" rel=\"noopener\">https:\/\/github.com\/intelligentbee\/iBeaconTest<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello, I got my hands on some interesting devices from Estimote called iBeacons which they are used for sending signals [&hellip;]<\/p>\n","protected":false},"author":28,"featured_media":2927,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73,79,80],"tags":[156,158],"yst_prominent_words":[],"post_mailing_queue_ids":[],"_links":{"self":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts\/2838"}],"collection":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/users\/28"}],"replies":[{"embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/comments?post=2838"}],"version-history":[{"count":5,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts\/2838\/revisions"}],"predecessor-version":[{"id":133061,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts\/2838\/revisions\/133061"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/media\/2927"}],"wp:attachment":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/media?parent=2838"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/categories?post=2838"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/tags?post=2838"},{"taxonomy":"yst_prominent_words","embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/yst_prominent_words?post=2838"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}