我正在尝试编写一个简单的应用程序,即使应用程序未处于活动状态,也会不断广播'beacon' . 我知道使用 CoreLocation 将在应用程序未使用时将其关闭,因此我尝试使用 Core Bluetooth 构建解决方案 . 麻烦的是我无法让应用程序开始做广告 .
import UIKit
import CoreBluetooth
class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralManagerDelegate {
var centralManager:CBCentralManager = CBCentralManager()
var peripheralManager:CBPeripheralManager = CBPeripheralManager()
let uuid:CBUUID = CBUUID(string: "DCEF54A2-31EB-467F-AF8E-350FB641C97B")
override func viewDidLoad() {
super.viewDidLoad()
self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
self.centralManager.delegate = self
let advertisingData = [CBAdvertisementDataLocalNameKey:"my-peripheral", CBAdvertisementDataServiceUUIDsKey: uuid]
peripheralManager.startAdvertising(advertisingData)
centralManager.scanForPeripheralsWithServices([uuid], options: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager, error: NSError?) {
print("started advertising")
print(peripheral)
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
print("peripheral discovered")
print("peripheral: \(peripheral)")
print("RSSI: \(RSSI)")
}
func centralManagerDidUpdateState(central: CBCentralManager) {
print("central state updated")
print(central.description)
if central.state == .PoweredOff {
print("bluetooth is off")
}
if central.state == .PoweredOn {
print("bluetooth is on")
let advertisingData = [CBAdvertisementDataLocalNameKey:"my-peripheral", CBAdvertisementDataServiceUUIDsKey: uuid]
let service = CBMutableService(type: uuid, primary: true)
self.peripheralManager.addService(service)
peripheralManager.startAdvertising(advertisingData)
centralManager.scanForPeripheralsWithServices(nil, options: nil)
}
if central.state == .Unsupported {
print("bluetooth is unsupported on this device")
}
}
func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
print("peripheral state updated")
print("\(peripheral.description)")
}
}
我已经在两台设备上安装了这个,问题似乎在于广告的传输,因为 peripheralManagerDidStartAdvertising()
永远不会被调用 .
1 回答
如果使用此init方法,则centralManagerDidUpdateState将起作用 . 如果要连续查看信标,可以设置CBCentralManagerScanOptionAllowDuplicatesKey选项 .