【发布时间】:2018-05-05 02:28:33
【问题描述】:
我试图让蓝牙在后台运行,我完全按照苹果文档中的描述设置了我的项目,但不知何故仍然没有在后台触发...我的设置:
Uses blueooth LE accessories
在项目功能集中,在 info.plist 中:
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
</array>
我的蓝牙服务单例:
import CoreBluetooth
class BluetoothService: NSObject {
var manager: CBCentralManager!
var characteristic: CBCharacteristic!
var peripheral: CBPeripheral!
let peripheral_name: String = "name"
let service_uuid: CBUUID = CBUUID(string: "uuid")
static let shared = BluetoothService()
private override init() {
super.init()
manager = CBCentralManager(delegate: self, queue: nil)
}
}
extension BluetoothService: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
print("centralManagerDidUpdateState: \(central.state.rawValue)")
if (central.state == CBManagerState.poweredOn) {
self.manager?.scanForPeripherals(withServices: [service_uuid], options: nil)
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
print("didDiscover peripheral")
if (peripheral.name == self.peripheral_name) {
self.manager.stopScan()
self.peripheral = peripheral
self.peripheral.delegate = self
self.manager.connect(peripheral, options: nil)
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("didConnect")
peripheral.discoverServices([service_uuid])
}
}
extension BluetoothService: CBPeripheralDelegate {
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
print("didDiscoverServices")
for service in peripheral.services! {
let currentService = service as CBService
}
}
...
}
当我启动应用程序时,它不会在前台和后台发现任何外围设备...
但是当我跑步时:
self.manager?.scanForPeripherals(withServices: nil, options: nil)
它只在前台工作。
谁能帮我解决这个问题?
谢谢和问候!
【问题讨论】:
标签: swift bluetooth background foreground discover