我一直在尝试在两台iOS设备之间设置“双向iBeacon通信”。我尝试使用This Technique on PubNub,我想我已设法启动发射器进行传输。但是,这两部手机都不匹配,如video所示。
由于我缺乏经验,本指南对我来说不太清楚,请查看我的代码。我收到的没有错误,两个iPhone上的项目工作正常,我可以看到Emitter正确传输,但是它们不匹配。
对于发射器和接收器,我已经导入了CoreLocation和CoreBluetooth框架,我通过单击“+”(未在源代码中编码)在info.plist中添加了“NSLocationAlwaysUsageDescription”和“NSLocationWhenInUseUsageDescription”。 / em>的
发射器代码:
class ViewController: UIViewController, CBPeripheralManagerDelegate {
var major = 9
var minor = 6
let uuid = NSUUID(UUIDString: "0CF052C2-97CA-407C-84F8-B62AAC4E9020")
var peripheralManager = CBPeripheralManager()
var advertisedData = NSDictionary()
}
override func viewDidLoad() {
super.viewDidLoad()
let region = CLBeaconRegion(proximityUUID: uuid, major: 9, minor: 6, identifier: "com.yourcampany.example")
self.advertisedData = region.peripheralDataWithMeasuredPower(nil)
self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil)
func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) {
switch peripheral.state {
case CBPeripheralManagerState.PoweredOn:
self.peripheralManager.startAdvertising(advertisedData)
self.powerON.text = "Power ON"
default:
break
}
}
收件人代码:
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet var label: UILabel!
var region = CLBeaconRegion()
var locationManager = CLLocationManager()
let uuid = NSUUID(UUIDString: "0CF052C2-97CA-407C-84F8-B62AAC4E9020")
override func viewDidLoad() {
super.viewDidLoad()
region = CLBeaconRegion(proximityUUID: uuid, identifier: "com.yourcampany.example")
self.locationManager.delegate = self
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startMonitoringForRegion(self.region)
}
func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: NSArray!, inRegion region: CLBeaconRegion!) {
var beacon = beacons.lastObject as CLBeacon
switch beacon.proximity {
case CLProximity.Immediate:
self.label.text = "Immediate"
case CLProximity.Near:
self.label.text = "Near"
default:
self.label.text = "AAA"
}
}
我的Main.storyboard上的标签未设置为“立即”,“近”或“AAA”中的任何值。
另外,如果我想传输一个字符串(由5-6个字符组成),最合乎逻辑的方法是什么。我已经读过它不可能发送大块数据但是一串几个字符怎么样? [可能使用 CentralManager 和 PeripheralManager ]
答案 0 :(得分:1)
您尚未致电self.locationManager.startRangingBeaconsInRegion(self.region)
。如果没有此调用,您将无法获得didRangeBeacons
委托方法的回调。您拨打了self.locationManager.startMonitoringForRegion(self.region)
,但这会调用didEnterRegion
& didExitRegion
委托方法。
所以你应该 -
override func viewDidLoad() {
super.viewDidLoad()
region = CLBeaconRegion(proximityUUID: uuid, identifier: "com.yourcampany.example")
self.locationManager.delegate = self
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startRangingBeaconsInRegion(self.region)
}
答案 1 :(得分:0)
您需要做的一件事是更改回调代码以操纵主线程上的UI。您必须像这样包装UI更改:
dispatch_async(dispatch_get_main_queue(),{
switch beacon.proximity {
case CLProximity.Immediate:
self.label.text = "Immediate"
case CLProximity.Near:
self.label.text = "Near"
default:
self.label.text = "AAA"
}
});