总的来说,我是 Swift 和 Mac/iOs 编程的新手。我正在使用 Xcode 7.3 在支持 BLE 并打开蓝牙的 Macbook Pro 上运行此示例。
import Foundation
import CoreBluetooth
func printState(state: CBCentralManagerState) {
switch state {
case CBCentralManagerState.PoweredOn:
print("owered on")
case CBCentralManagerState.PoweredOff:
print("owered off")
case CBCentralManagerState.Resetting:
print("Resetting")
case CBCentralManagerState.Unauthorized:
print("Unauthorized")
case CBCentralManagerState.Unknown:
print("Unknown")
default:
print ("Unsupported")
}
}
var myCentralManager = CBCentralManager(delegate:nil, queue:nil)
while true {
printState(myCentralManager.state)
sleep(1)
}
代码一遍又一遍地打印出“未知”,即使在几分钟后也是如此。我也尝试过设置委托(delegate),但没有调用 didUpdateState 回调。我也尝试从命令行和 Swift 解释器运行它并得到相同的结果。
我一定遗漏了一些非常基本的东西。如何让它报告 CBCentralManager 已开机?
Best Answer-推荐答案 strong>
据我所知,如果您不使用文档中列出的两个初始化程序之一,这就是结果——您想使用其中一个:
init(delegate:queue
或:
init(delegate:queueptions
如果您只是调用,Xcode 不会提示:
CBCentralManager()
但如果你这样做,你似乎会无限期地留在 CBCentralManagerState.Unknown 中。
如果您想进行实验,请创建一个 Playground 并粘贴此代码,然后使用我列出的两个初始化程序变体进行尝试:
import Cocoa
import CoreBluetooth
import XCPlayground
@objc
public class BluetoothWatcher: NSObject, CBCentralManagerDelegate {
var cbcm: CBCentralManager!;
var timer: NSTimer!;
override init() {
super.init();
/*:
When you initialize a central manager, the delegate seems important. If you comment out the initializer with the delegate and uncomment the other one, it'll stay in state unknown indefinitely.
*/
//cbcm = CBCentralManager(delegate: self, queue:nil);
cbcm = CBCentralManager();
checkStateInOneSecond();
}
public func centralManagerDidUpdateState(central: CBCentralManager) {
print( "State updated: \(stateString())" );
}
func checkStateInOneSecond() {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), {
self.checkState();
});
}
public func checkState() {
print( "Timer fired, state: \(stateString())" );
checkStateInOneSecond();
}
func stateString() -> String {
switch(cbcm.state) {
case .Resetting:
return "resetting"
case .PoweredOn:
return "powered on";
case .PoweredOff:
return "powered off";
case .Unknown:
return "unknown";
case .Unsupported:
return "unsupported";
case .Unauthorized:
return "unauthorized";
}
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true;
var watcher = BluetoothWatcher();
你会看到委托(delegate),它从 Unknown 开始,几乎立即委托(delegate)被调用,状态更改为 PoweredOn ,并且每个后续计时器触发都会显示开机 .
在没有委托(delegate)的情况下做同样的事情,使用空的初始化器,委托(delegate)方法将永远不会被调用(不足为奇),计时器触发将继续显示 Unknown 。
关于ios - 核心蓝牙 CBCentralManager 在 Mac 上总是将状态报告为未知,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/36815274/
|