简体   繁体   中英

How to detect a new iBeacon?

I range beacons and display them in my TableView. I need to detect when my app detects a new beacon. I try to do it in this way, but something goes wrong

var oldBeacons: [CLBeacon] = []

func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
  for beacon in beacons {
    for oldBeacon in oldBeacons {
      if beacon.minor != oldBeacon.minor, beacon.major != oldBeacon.major {
        print("New Beacon")
      } else {
        print("Old Beacon")
      }
    }
  }
  oldBeacons = beacons
}

Iterating through two arrays won't easily work because if you ever see two beacons at the same time, you'll incorrectly think they are "new" because one is not the same as the other.

I typically use a Set to do this:

var detectedBeacons: Set<String>

func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
  for beacon in beacons {
    let key = "\(beacon.proximityUUID) \(beacon.major) \(beacon.minor)"
    if detectedBeacons.contains(key) {
      print("Old Beacon")
    }
    else {
      print("New Beacon")
      detectedBeacons.insert(key)
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM