CBCentralManager可以扩展自定义协议吗?我们可以覆盖CBCentralManagerDelegate吗?

时间:2017-09-22 16:37:16

标签: ios objective-c xcode swift3 core-bluetooth

//自定义类

public protocol BluetoothManagerProtocol {
    var delegate: CBCentralManagerDelegate? {get set}
    //var state: CBCentralManagerState { get }

    func scanForPeripheralsWithServices(serviceUUIDs: [CBUUID]?, options: [String : AnyObject]?)
    func stopScan()
    func connectPeripheral(peripheral: CBPeripheral, options: [String : AnyObject]?)
    func connectPeripheral(peripheral: BluetoothPeripheral, options: [String : AnyObject]?)
}

extension CBCentralManager : BluetoothManagerProtocol {
    public func connectPeripheral(peripheral: CBPeripheral, options: [String : AnyObject]?) {
        //
    }

    public func scanForPeripheralsWithServices(serviceUUIDs: [CBUUID]?, options: [String : AnyObject]?) {
        //
    }

    public func connectPeripheral(peripheral: BluetoothPeripheral, options: [String : AnyObject]?) {
        guard let peripheral = peripheral as? CBPeripheral else {
            return
        }
        connectPeripheral(peripheral, options: options)
    }
}

extension CBCentralManagerDelegate{
    func centralManager(central: BluetoothManagerProtocol, didDiscoverPeripheral peripheral: BluetoothPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {}

func centralManager(central: BluetoothManagerProtocol,didConnectPeripheral peripheral:BluetoothPeripheral) {}

func centralManagerDidUpdateState(central: BluetoothManagerProtocol) {}

func centralManager(central: BluetoothManagerProtocol, didDisconnectPeripheral peripheral: BluetoothPeripheral, error: NSError?) {}
}

我刚刚进入Swift中的协议和代理的高级主题。我很惊讶,CBCentralManager可以扩展自定义协议吗? 如何使用自定义协议对CBCentralManagerDelegate方法进行参数化? 这背后的概念是什么?究竟需要什么?

这是用swift 2.3编写的。这个策略会在Swift 4.0中运行吗?

1 个答案:

答案 0 :(得分:1)

是的,CBCentralManager来自Core Bluetooth框架,可以包含自定义协议定义。遵循这种方法来利用TDD - 测试驱动开发。

由于单元测试蓝牙功能使同步设备变得困难,开发人员通过创建自己的自定义方法而不是使用Apple for iOS Frameworks提供的方法,利用依赖注入来模拟方法。

您可以为UIView,UIColor等提供自己的自定义方法。

例如



class MockCBCentralManager : BluetoothManagerProtocol {
    var delegate: CBCentralManagerDelegate?
    var scanCalled: Bool = false
    var connectPeripheralCalled = false
    fileprivate var internalState: CBCentralManagerState = .unknown
    var state: CBCentralManagerState {
        get {
            return internalState
        }
    }
}
 func scanForPeripheralsWithServices(_ serviceUUIDs: [CBUUID]?, options[String : AnyObject]?) 
{
  scanCalled = true
  let advertisementData = 
  [CBAdvertisementDataServiceUUIDsKey : 
  [STUDENT_APP_UUID],CBAdvertisementDataLocalNameKey:"MockPeripheral"]           
                
  let mock = MockPeripheral()         
  (delegate as? CentralManager)?.centralManager(self, 
  didDiscoverPeripheral: mock, advertisementData: 
  advertisementData,RSSI: 90) 
    
 }




可在以下网址找到更多信息 https://nomothetis.svbtle.com/the-ghost-of-swift-bugs-future

干杯!