iBeacon Basic Operation

suggest change

This 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.

  1. 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)
}
  1. 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!)
    }
}
  1. Location manager range beacon
func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
    print(beacons.first?.major)
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents