-
Notifications
You must be signed in to change notification settings - Fork 1
/
ViewController.swift
76 lines (61 loc) · 2.32 KB
/
ViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//
// ViewController.swift
// DetectABeacon
//
// Created by Julian Moorhouse on 16/08/2019.
// Copyright © 2019 Mindwarp Consultancy Ltd. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet 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 locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
if let beacon = beacons.first {
update(distance: beacon.proximity)
} else {
update(distance: .unknown)
}
}
func startScanning() {
// test beacon uuid
let uuid = UUID(uuidString: "5A4BCFCE-174E-4BAC-A814-092E77F6B7E5")!
let beaconRegion = CLBeaconRegion(proximityUUID: uuid, major: 123, minor: 456, identifier: "MyBeacon")
locationManager?.startMonitoring(for: beaconRegion)
locationManager?.startRangingBeacons(in: beaconRegion)
}
func update(distance: CLProximity) {
UIView.animate(withDuration: 1) {
switch distance {
case .far:
self.view.backgroundColor = .blue
self.distanceReading.text = "FAR"
case .near:
self.view.backgroundColor = .orange
self.distanceReading.text = "NEAR"
case .immediate:
self.view.backgroundColor = .red
self.distanceReading.text = "RIGHT HERE"
default:
self.view.backgroundColor = .gray
self.distanceReading.text = "UNKNOWN"
}
}
}
}