1

I want to use a ıos phone as an ibeacon. I used The following code. Advertising started when app in foreground but not working when screen locked or app in background. I used BackgroundModes "Act as a Bluetooth LE acssories" and "Bluetooth Peripheral Usage Description".

  var localBeacon: CLBeaconRegion!
  var beaconPeripheralData: NSDictionary!
  var peripheralManager: CBPeripheralManager!
  let localBeaconUUID = "XXX"
  let localBeaconMajor: CLBeaconMajorValue = 0
  let localBeaconMinor: CLBeaconMinorValue = 0
  let identifier = "allbeacons"

  override init() {
    super.init()

  }
  func initLocalBeacon() {
    if localBeacon != nil {
      stopLocalBeacon()
    }
    let uuid = UUID(uuidString: localBeaconUUID)!
    localBeacon = CLBeaconRegion(proximityUUID: uuid, major: localBeaconMajor, minor: localBeaconMinor, identifier: identifier)
    beaconPeripheralData = localBeacon.peripheralData(withMeasuredPower: nil)
    peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil)
  }

  func stopLocalBeacon() {
    peripheralManager.stopAdvertising()
    peripheralManager = nil
    beaconPeripheralData = nil
    localBeacon = nil
  }

  func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
    if peripheral.state == .poweredOn {
      peripheralManager.startAdvertising(beaconPeripheralData as? [String: Any])
    }
    else if peripheral.state == .poweredOff {
      peripheralManager.stopAdvertising()
    }
}

0 Answers0