如何在iOS中将iOS设备用作iBeacon?

时间:2017-11-13 10:17:34

标签: ios iphone swift ibeacon

我是信标集成的新手。使用代码获取iPhone信标(发射器)的UUID。 最初,我写了下面的代码,让iPhone的UUID充当灯塔

let uuidString = UIDevice.current.identifierForVendor?.uuidString  
print("UUID == \(uuidString)")

UUID:F2830580-4E97-4098-B01A-99D49BB69EF1

var locationManager: CLLocationManager?
var myBeaconRegion: CLBeaconRegion?
var peripheral: CBPeripheral?
var manager: CBCentralManager?
var peripheralManager: CBPeripheralManager?

override func viewDidLoad(){

    super.viewDidLoad()
    locationManager = CLLocationManager()
    locationManager?.delegate = self
    locationManager?.distanceFilter = kCLDistanceFilterNone
    locationManager?.desiredAccuracy = kCLLocationAccuracyBest
    locationManager?.requestAlwaysAuthorization()
    locationManager?.requestWhenInUseAuthorization()
    peripheralManager = CBPeripheralManager(delegate: self as 
    CBPeripheralManagerDelegate, queue: nil, options: nil)

    let uuid = UUID(uuidString: "F2830580-4E97-4098-B01A-99D49BB69EF1")

    myBeaconRegion = CLBeaconRegion(proximityUUID: uuid!,identifier: "iBeacon")

    myBeaconRegion?.notifyOnEntry = true
    myBeaconRegion?.notifyOnExit = true
    myBeaconRegion?.notifyEntryStateOnDisplay = true
    manager = CBCentralManager(delegate: self as? CBCentralManagerDelegate, queue: nil)
    locationManager?.startMonitoring(for: myBeaconRegion!)
    locationManager?.startRangingBeacons(in: myBeaconRegion!)
    locationManager?.pausesLocationUpdatesAutomatically = false
    locationManager?.startUpdatingLocation()

}

使用委托方法获取检测到的信标

func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion)
{

  //  let value = region.major  as? NSNumber
   beaconLabel.text = "Beacon not found!"
    let foundBeacon = beacons.first as? CLBeacon
    print("foundBeacon == \(foundBeacon)")
 guard let  discoveredBeacon = beacons.first?.proximity else {
 print("beacon not found")
 return
 }


    let proxyValue = foundBeacon?.accuracy
    beaconDistanceLabel.text = String(describing: proxyValue!)
 let background:UIColor = {

 switch discoveredBeacon {
 case .immediate:
    beaconLabel.text = "Immediate!"
    return  UIColor.green
 case .near:
    beaconLabel.text = "Near!"
    return  UIColor.orange
 case .far:
    beaconLabel.text = "Far!"
    return  UIColor.red
 case .unknown:
    beaconLabel.text = "Unknown!"
    return  UIColor.magenta
 }
 }()
 view.backgroundColor = background

}

委托方法正在调用,但CLBeacon未检测到iPhone设备。

即使我尝试过 https://developer.apple.com/documentation/corelocation/turning_an_ios_device_into_an_ibeacon但没有结果。

任何帮助将不胜感激..

1 个答案:

答案 0 :(得分:0)

你可以在任何iOS设备上创建估计信标,使你的设备成为发射机..

利用信标模拟器应用程序并手动创建信标。 现在运行你的应用程序并监控信标范围......在代码中用相同的信标代码进行测试..