gpt4 book ai didi

swift - iOS - Swift 3 - 蓝牙背景

转载 作者:行者123 更新时间:2023-11-30 11:59:36 24 4
gpt4 key购买 nike

我正在尝试让蓝牙在后台运行,并且我完全按照苹果文档中的描述设置我的项目,但不知何故仍然不会在后台触发...我的设置:

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)

它仅在前台运行。

有人可以帮我解决这个问题吗?

最佳答案

在您运行的代码中

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

对您有用的是:

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

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

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

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

关于swift - iOS - Swift 3 - 蓝牙背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47416256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com