【发布时间】:2015-02-21 14:01:30
【问题描述】:
我需要检测设备何时进入或退出某个区域并基于此执行一些操作。
使用“startRangingBeaconsInRegion”,我可以检测到最近的 iBeacon 并据此更改背景颜色,如果无法检测到 iBeacon,则更改为白色。
我无法让它在“didEnterRegion”或“didExitRegion”上触发。
我知道如果设备已经在该区域中,则 enterRegion 不会触发。我确保未检测到信标(白屏),然后检测到信标(彩色屏幕) - 但没有任何反应。
我尝试过使用 estimote SDK,但遇到了同样的问题。重新启动设备也没有帮助。
我的代码如下,有什么建议吗?
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
let region = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D"), identifier: "Estimotes")
let colors = [
3861: UIColor(red: 84/255, green: 77/255, blue: 160/255, alpha: 1),
19152: UIColor(red: 142/255, green: 212/255, blue: 220/255, alpha: 1),
40527: UIColor(red: 162/255, green: 213/255, blue: 181/255, alpha: 1)
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
locationManager.pausesLocationUpdatesAutomatically = false
region.notifyEntryStateOnDisplay = true
region.notifyOnEntry = true
region.notifyOnExit = true
// Request authorisation to track location
if (CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedWhenInUse) {
locationManager.requestWhenInUseAuthorization()
}
if (CLLocationManager .isMonitoringAvailableForClass(CLBeaconRegion))
{
println("OK")
}
else {
println("Problem")
}
locationManager.startMonitoringForRegion(region)
locationManager.startRangingBeaconsInRegion(region)
locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) {
let knownBeacons = beacons.filter { $0.proximity != CLProximity.Unknown }
if (knownBeacons.count > 0) {
let closestBeacon = knownBeacons[0] as CLBeacon
self.view.backgroundColor = self.colors[closestBeacon.minor.integerValue]
println(beacons)
}
else {
self.view.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)
}
}
func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
println("Region entered")
}
func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) {
println("Region exited")
}
func locationManager(manager: CLLocationManager!, monitoringDidFailForRegion region: CLRegion!, withError error: NSError!) {
println("FAIL!")
}
}
【问题讨论】:
标签: ios swift ibeacon estimote