iBeacon Basic Operation
suggest changeThis is Swift 2 (NSUUID, startMonitoringForRegion, isKindOfClass). locationManager, beacon, and BeaconHandler must already exist. BeaconHandler is unused. requestAlwaysAuthorization needs the Always location usage description in Info.plist. The availability check originally ran after monitoring had started, and startRangingBeaconsInRegion used self.beacon, which this method never set. NSUUID(UUIDString:) is optional. beacons.first is optional, so the ranging callback cannot read .major on it directly.
- Set up beacon monitoring
func initiateRegion(ref: BeaconHandler) {
let uuid = NSUUID(UUIDString: "<UUID>")
let beaconRegion = CLBeaconRegion(proximityUUID: uuid!, identifier: "")
self.beacon = beaconRegion
locationManager?.requestAlwaysAuthorization()
beaconRegion.notifyOnEntry = true
beaconRegion.notifyOnExit = true
beaconRegion.notifyEntryStateOnDisplay = true
if !CLLocationManager.isMonitoringAvailableForClass(CLBeaconRegion) {
print("error")
return
}
locationManager?.startMonitoringForRegion(beaconRegion)
locationManager?.delegate = self
locationManager?.startRangingBeaconsInRegion(beaconRegion)
}
- Location manager enter and exit region
func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {
if region.isKindOfClass(CLBeaconRegion) {
locationManager?.startRangingBeaconsInRegion(self.beacon!)
}
}
func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) {
if region.isKindOfClass(CLBeaconRegion) {
locationManager?.stopRangingBeaconsInRegion(self.beacon!)
}
}
- Location manager range beacon
func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
print(beacons.first?.major)
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents