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连接无效”
我确实尝试将 NSBluetoothPeripheralUsageDescription 添加到我的info.plist文件中,但这不起作用。
奇怪的是,如果我直接初始化 CBCentralManager 而不是使用类,那么一切正常。
当我尝试通过创建类 BLE 的对象或任何其他类来初始化 CBCentralManager 时,才会出现此问题。
答案 0 :(得分:2)
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)
}
}
答案 1 :(得分:1)
答案 2 :(得分:1)
对于正在运行iOS模拟器的用户,蓝牙无法在其中运行。因此,如果您尝试使用蓝牙模拟应用程序,则会引发“ [CoreBlueooth] XPC连接无效”错误。
有关更多信息:https://www.browserstack.com/test-on-ios-simulator
您需要在真实设备上测试您的应用。
答案 3 :(得分:0)
以我为例,事实证明我打电话给Scan太早了。我正在从ViewDidLoad方法进行调用。如果我通过按一下按钮启动扫描,则扫描效果会很好。
我使用的解决方法是从ViewDidLoad方法调用扫描时延迟使用performSelector。
答案 4 :(得分:0)
我解决了在经理类中将 NSObject 更改为 UIViewController 的问题