Last active
October 11, 2018 22:31
-
-
Save Tulakshana/3cefa69da817bdf3e7e7b7f7b72d9105 to your computer and use it in GitHub Desktop.
Using this class you can make an iPhone behave like an iBeacon :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import CoreBluetooth | |
import CoreLocation | |
class Beacon: NSObject { | |
static let shared = Beacon() | |
var localBeacon: CLBeaconRegion! | |
var beaconPeripheralData: [String: AnyObject]? | |
var peripheralManager: CBPeripheralManager! | |
func startLocalBeacon() { | |
if localBeacon != nil { | |
stopLocalBeacon() | |
} | |
let localBeaconUUID = "5A4BCFCE-174E-4BAC-A814-092E77F6B7E5" | |
let localBeaconMajor: CLBeaconMajorValue = 123 | |
let localBeaconMinor: CLBeaconMinorValue = 456 | |
let identifier = "mybeacon" | |
let uuid = UUID(uuidString: localBeaconUUID)! | |
localBeacon = CLBeaconRegion(proximityUUID: uuid, major: localBeaconMajor, minor: localBeaconMinor, identifier: identifier) | |
beaconPeripheralData = localBeacon.peripheralData(withMeasuredPower: nil) as? [String: AnyObject] | |
peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil) | |
} | |
func stopLocalBeacon() { | |
peripheralManager.stopAdvertising() | |
peripheralManager = nil | |
beaconPeripheralData = nil | |
localBeacon = nil | |
} | |
} | |
extension Beacon: CBPeripheralManagerDelegate { | |
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { | |
if peripheral.state == .poweredOn { | |
if let data = beaconPeripheralData { | |
peripheralManager.startAdvertising(data) | |
} | |
} else if peripheral.state == .poweredOff { | |
peripheralManager.stopAdvertising() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment