我是Swift和Mac / iO编程的新手。我在Macbook Pro上运行此示例,支持BLE并使用Xcode 7.3打开蓝牙。
import Foundation
import CoreBluetooth
func printState(state: CBCentralManagerState) {
switch state {
case CBCentralManagerState.PoweredOn:
print("Powered on")
case CBCentralManagerState.PoweredOff:
print("Powered 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)
}
代码打印出来"未知"一遍又一遍,即使在很多分钟之后。我也尝试过设置委托,但是没有调用didUpdateState回调。我也尝试从命令行和Swift解释器运行它并得到相同的结果。
我必须遗漏一些非常基本的东西。如何报告CBCentralManager已启动?
答案 0 :(得分:3)
我可以说,如果您不使用文档中列出的两个初始值设定项之一,那就是结果 - 您要使用其中一个:
init(delegate:queue:)
或:
init(delegate:queue:options:)
如果你打电话,Xcode不会抱怨:
CBCentralManager()
但如果你这样做,似乎你将无限期地留在CBCentralManagerState.Unknown
。
如果您想进行实验,请在游乐场中粘贴此代码,然后使用我列出的两个初始化程序变体进行尝试:
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();
您将与代理人一起查看,它从Unknown
开始,几乎立即调用委托,状态更改为PoweredOn
,并且每个后续计时器显示{{1} }。
在没有委托的情况下执行相同的操作,使用空的初始化程序,并且永远不会调用委托方法(毫不奇怪)并且计时器触发将继续显示PoweredOn
。