Skip to content

Instantly share code, notes, and snippets.

@FromAtom
Created August 23, 2024 07:58
Show Gist options
  • Save FromAtom/807ec478e77ec87b55f264568cf080ea to your computer and use it in GitHub Desktop.
Save FromAtom/807ec478e77ec87b55f264568cf080ea to your computer and use it in GitHub Desktop.
iosdc-2024-ibeacon
import UIKit
import CoreLocation
final class ViewController: UIViewController {
private let locationManager: CLLocationManager = CLLocationManager()
private var beaconResion: CLBeaconRegion!
let uuid = UUID(uuidString: "41462998-6CEB-4511-9D46-1F7E27AA6572")!
let major = CLBeaconMajorValue(18)
let minor = CLBeaconMinorValue(5)
@IBOutlet weak var label: UILabel!
@IBAction func ButtonTapped(_ sender: UIButton) {
label.text = ""
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 1
if locationManager.authorizationStatus == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
}
private func startMonitoring() {
beaconResion = CLBeaconRegion(uuid: uuid, major: major, minor: minor, identifier: "iosdc")
beaconResion.notifyEntryStateOnDisplay = false
beaconResion.notifyOnEntry = true
beaconResion.notifyOnExit = true
locationManager.startMonitoring(for: beaconResion)
locationManager.startRangingBeacons(satisfying: beaconResion.beaconIdentityConstraint)
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
switch manager.authorizationStatus {
case .authorizedAlways, .authorizedWhenInUse:
startMonitoring()
return
case .notDetermined:
print("notDetermined")
case .denied:
print("denied")
case .restricted:
print("restricted")
@unknown default:
fatalError("将来増えるやつ")
}
}
func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) {
manager.requestState(for: region)
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
switch (state) {
case .inside:
label.text = "inside"
case .outside, .unknown:
label.text = "outside"
}
}
func locationManager(_ manager: CLLocationManager, didRange beacons: [CLBeacon], satisfying beaconConstraint: CLBeaconIdentityConstraint) {
for beacon in beacons {
guard beacon.uuid == uuid else {
continue
}
switch beacon.proximity {
case .near:
label.text = "near"
case .immediate:
label.text = "immediate"
case .far:
label.text = "far"
default:
label.text = "unknown"
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment