ビーコンまでの距離の決定
ビーコン領域観測
Info.plistのRequired device capabilitiesにlocation-services追加
Info.plistのInformation Property ListにNSLocationAlwaysUsageDescriptionを追加して、許可を求めるダイアログに表示する文字列を設定
ViewController.swift
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var proximityLabel: UILabel!
@IBOutlet weak var decibelLabel: UILabel!
var myLocationManager: CLLocationManager!
var beaconRegion: CLBeaconRegion!
override func viewDidLoad() {
super.viewDidLoad()
if !CLLocationManager.isMonitoringAvailableForClass(CLCircularRegion) {
return
}
let status = CLLocationManager.authorizationStatus()
if status == CLAuthorizationStatus.Restricted || status == CLAuthorizationStatus.Denied {
return
}
myLocationManager = CLLocationManager()
myLocationManager.delegate = self
if status == CLAuthorizationStatus.NotDetermined {
myLocationManager.requestAlwaysAuthorization()
}
if !CLLocationManager.locationServicesEnabled() {
return
}
if UIApplication.sharedApplication().backgroundRefreshStatus != UIBackgroundRefreshStatus.Available {
return
}
let myProximityUUID = NSUUID.init(UUIDString: "YourUUID")
beaconRegion = CLBeaconRegion.init(proximityUUID: myProximityUUID!, major: 0, minor: 0, identifier: "YourUniqueIdentifier")
beaconRegion.notifyOnEntry = false
beaconRegion.notifyEntryStateOnDisplay = true
beaconRegion.notifyOnExit = true
myLocationManager.startMonitoringForRegion(beaconRegion)
myLocationManager.requestStateForRegion(beaconRegion)
}
func locationManager(manager: CLLocationManager, didDetermineState state: CLRegionState, forRegion region: CLRegion) {
if state == CLRegionState.Inside {
statusLabel.text = "範囲内"
} else {
statusLabel.text = "範囲外"
}
}
func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {
statusLabel.text = "侵入"
}
func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) {
statusLabel.text = "離脱"
}
func locationManager(manager: CLLocationManager, monitoringDidFailForRegion region: CLRegion?, withError error: NSError) {
statusLabel.text = "失敗"
}
ビーコンまでの距離決定
ViewController.swift
statusLabel.text = "失敗"
}
func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
if beacons.count > 0 {
let nearestBeacon = beacons[0]
if CLProximity.Unknown == nearestBeacon.proximity {
proximityLabel.text = "不明"
} else {
switch nearestBeacon.proximity {
case CLProximity.Far:
proximityLabel.text = "遠い"
case CLProximity.Near:
proximityLabel.text = "近い"
default:
statusLabel.text = "目の前"
}
decibelLabel.text = String(nearestBeacon.rssi)
}
}
}
func startRangingBeacons() {
if CLLocationManager.isRangingAvailable() {
myLocationManager.startRangingBeaconsInRegion(beaconRegion)
}
}
func stopRangingBeacons() {
if CLLocationManager.isRangingAvailable() {
myLocationManager.stopRangingBeaconsInRegion(beaconRegion)
}
}