CLBeaconRegion이란?
iBeacon 기기의 존재를 감지하는 데 사용되는 영역입니다.
사용자의 위치정보는 민감한 정보이므로 Apple은 다음을 지정해놓았습니다.
앱이 비콘을 백그라운드에서 감지할 수 있도록 Always access를 요청할 것이지만, 위의 규칙들 때문에 info.plist에 아래의 두 가지를 모두 추가해 줍니다.
import CoreLocation
var locationManager : CLLocationManager?
위와 같은 과정이 실제로 locationManager를 생성하지는 않습니다.
class ViewController: UIViewController, CLLocationManagerDelegate {
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.requestAlwaysAuthorization()
}
CLLocationManager() 객체에 대한 대리자로 뷰컨트롤러를 설정했기 때문에, 사용자의 응답을 뷰컨트롤러가 알 수 있고 아래의 메서드가 호출됩니다.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways {
if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
if CLLocationManager.isRangingAvailable() {
// do stuff
}
}
}
}
Core Location 세팅이 끝났다면, 다음을 사용하여 비콘의 범위를 지정할 수 있습니다.
CLBeaconRegion의 실행을 위해서는 시뮬레이터가 아닌 실제 기기를 사용해야하고, 기기에 locate beacon 앱을 설치해야합니다.
비콘은 아래의 세 가지 정보를 사용하여 식별됩니다.
func startScanning() {
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)
}
위의 didChangeAuthorization //do stuff아래에 startScanning()메서드를 추가하여
사용자가 허가하고, 기기가 비콘을 모니터링 할 수 있는 경우 실행하도록 합니다.
비콘과의 근접성을 반영하여 UI가 변경될 수 있도록 해줍니다.
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
if let beacon = beacons.first {
update(distance: beacon.proximity)
} else {
update(distance: .unknown)
}
}
func update(distance: CLProximity) {
UIVIew.animate(withDuration: 0.8) {
switch distance {
case .far:
self.view.backgroundColor = UIColor.gray
self.distanceReading.text = "FAR"
case .near:
self.view.backgroundColor = UIColor.blue
self.distanceReading.text = "NEAR"
case .immediate:
self.view.backgroundColor = UIColor.orange
self.distanceReading.text = "RIGHT HERE"
default:
self.view.backgroundColor = UIColor.gray
self.distanceReading.text = "UNKNOWN"
}
}
}