【问题标题】:iOS - Swift 3 - Bluetooth backgroundiOS - Swift 3 - 蓝牙背景
【发布时间】: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


    【解决方案1】:

    在您运行的代码中

    self.manager?.scanForPeripherals(withServices: [service_uuid], options: nil)
    

    对你有用的是:

    self.manager?.scanForPeripherals(withServices: nil, options: nil)
    

    不同之处在于您在示例中定义了 withServices 。如果您使用服务搜索外围设备,您需要确保 serviceUUID 是您的蓝牙设备的广告数据的一部分。可能外围设备有服务,但这并不意味着它将成为您的广告数据的一部分。

    附带信息:如果您运行 scanForPeripherals 并且 withServices 为 nil,它将不会在后台运行。对于后台执行,您需要定义服务。

    附:如果您扫描并找到外围设备 didDiscover 将被调用。一个变量是“advertisementData”。这将是检查您是否想知道您的 serviceUUID 是否是广告数据的一部分的变量。

    【讨论】:

    • 你能分享一个关于如何通过在前台扫描设备来打印 UUIDs 服务的代码示例吗?
    猜你喜欢
    • 2020-12-09
    • 2016-01-11
    • 1970-01-01
    • 2020-03-25
    • 2018-03-04
    • 2015-11-23
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    相关资源
    最近更新 更多