In project 22, the background color is blinking between (any color) and grey if there is
else {
update(distance: .unknown)
}
In locationmanager(didrangebeacons) function.
If I remove the line it works alright.
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var hasShownNotification = false
@IBOutlet weak var uuuidIdentifier: UILabel!
var uuids = [String]()
@IBOutlet weak var distanceReading: UILabel!
var locationManager: CLLocationManager?
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.requestAlwaysAuthorization()
view.backgroundColor = .gray
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways {
if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
if CLLocationManager.isRangingAvailable() {
startScanning() }
}
}
}
func startScanning() {
uuids = ["5A4BCFCE-174E-4BAC-A814-092E77F6B7E5", "2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6", "E2C56DB5-DFFB-48D2-B060-D0F5A71096E0"]
for (number,uuidString) in uuids.enumerated() {
let uuid = UUID(uuidString: uuidString)!
let beaconIdentity = CLBeaconIdentityConstraint(uuid: uuid, major: 123, minor: 456)
let beaconRegion = CLBeaconRegion(beaconIdentityConstraint: beaconIdentity, identifier: "MyBeacon\(number)")
locationManager?.startMonitoring(for: beaconRegion)
locationManager?.startRangingBeacons(satisfying: beaconIdentity)
}
}
func update(distance: CLProximity) {
UIView.animate(withDuration: 1) {
switch distance {
case .far:
self.view.backgroundColor = UIColor.blue
self.distanceReading.text = "FAR"
case .near:
self.view.backgroundColor = UIColor.orange
self.distanceReading.text = "NEAR"
case .immediate:
self.view.backgroundColor = UIColor.red
self.distanceReading.text = "RIGHT HERE"
case .unknown:
self.view.backgroundColor = UIColor.gray
self.distanceReading.text = "UNKNOWN"
self.uuuidIdentifier.text = "UNKNOWN"
@unknown default:
self.view.backgroundColor = UIColor.red
self.distanceReading.text = "UNKNOWN"
self.uuuidIdentifier.text = "UNKNOWN"
}
}
}
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
print("called")
if let beacon = beacons.first {
if hasShownNotification == false {
hasShownNotification = true
let ac = UIAlertController(title: "Beacon detected", message: "Beacon has been detected", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
for uuid in uuids {
if uuid == beacon.uuid.uuidString {
self.uuuidIdentifier.text = uuid
update(distance: beacon.proximity)
}
}
}
else {
update(distance: .unknown)
}
}
}
Is it possible that the function is called more often than the beacon is transmitting and that is the cause?