public class BLE: NSObject, CBCentralManagerDelegate {
var centralManager:CBCentralManager!
public override init() {
super.init()
self.centralManager = CBCentralManager.init(delegate: self, queue: nil)
}
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .unknown:
print("unknown")
case .resetting:
print("resetting")
case .unsupported:
print("unsupported")
case .unauthorized:
print("unauthorized")
case .poweredOff:
print("powered off")
case .poweredOn:
print("powered on")
self.centralManager.scanForPeripherals(withServices: nil, options: nil)
}
}
}
这是我的代码,每当我运行它时,它都会给我消息
“[CoreBlueooth] XPC Connection Invalid”
我曾尝试将 NSBluetoothPeripheralUsageDescription 添加到我的 info.plist 文件中,但没有成功。
奇怪的是,如果我直接初始化 CBCentralManager 而不是使用类,那么一切正常。
只有当我尝试通过创建类 BLE 或任何其他类的对象来初始化 CBCentralManager 时,才会出现此问题。
最佳答案
CBCentralManager 的引用应该是作为成员变量的类的强引用。它不能用作本地引用。
下一步试试:
class ViewController: UIViewController {
var ble: BLE!
override func viewDidLoad() {
super.viewDidLoad()
ble = BLE()
}
}
class BLE: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
private var manager: CBCentralManager!
required override init() {
super.init()
manager = CBCentralManager.init(delegate: self, queue: nil)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
var consoleLog = ""
switch central.state {
case .poweredOff:
consoleLog = "BLE is powered off"
case .poweredOn:
consoleLog = "BLE is poweredOn"
case .resetting:
consoleLog = "BLE is resetting"
case .unauthorized:
consoleLog = "BLE is unauthorized"
case .unknown:
consoleLog = "BLE is unknown"
case .unsupported:
consoleLog = "BLE is unsupported"
default:
consoleLog = "default"
}
print(consoleLog)
}
}
关于swift - CoreBluetooth XPC 连接无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49917646/