代表们不工作

时间:2016-06-30 13:38:12

标签: swift delegates

我正在编写代码来连接到BLE设备,然后将它们列在表中以连接或断开它们。我对外围设备和经理角色感到满意,并了解如何访问BLE设备。以前我使用过NSNotifications,但宁愿让代表们管理通知。

下面的代码很简单,就扫描设备然后提示代表而言,但代表没有响应。

请帮忙......

代表

import UIKit
import CoreBluetooth

protocol BLEDelegate {

    func bleDidConnectToPeripheral(sender: BLEDiscovery, peripheral: CBPeripheral)

}

let bleDiscoverySharedInstance = BLEDiscovery()

//MARK: - UUIDS for StingRay Genessis M (SRG)
let StingRayGenesisMUUID    = CBUUID    (string: "346D0000-12A9-11CF-1279-81F2B7A91332") //Core UUID


//MARK: - UUIDS for StingRay Genessis HR (SRG)
let StingRayGenesisHRUUID   = CBUUID    (string: "F9AB0000-3F75-4668-9BAC-F8264DAE7820") //Core UUID

//MARK: - Device and Characteristic Registers
var BLEDevices          : [CBPeripheral] = []           //Device Array
var BLECharDictionary   = [String: CBCharacteristic]()  //Characteristic Dictionary


class BLEDiscovery: NSObject, CBCentralManagerDelegate {

    private var centralManager : CBCentralManager?

    var delegate: BLEDelegate?

    override init() {
        super.init()

        let centralStingRayBLEQueue = dispatch_queue_create("com.stingray", DISPATCH_QUEUE_SERIAL)
        centralManager = CBCentralManager(delegate: self, queue: centralStingRayBLEQueue)


    }

    // MARK: - CB centralManager
    func centralManagerDidUpdateState(central: CBCentralManager) {
        switch (central.state) {

            case CBCentralManagerState.PoweredOff:
                print("CBCentralManagerState.PoweredOff")

            case CBCentralManagerState.Unauthorized:
                // Indicate to user that the iOS device does not support BLE.
                print("CBCentralManagerState.Unauthorized")
                break

            case CBCentralManagerState.Unknown:
                // Wait for another event
                print("CBCentralManagerState.Unknown")
                break

            case CBCentralManagerState.PoweredOn:
                print("CBCentralManagerState.PoweredOn")
                self.startScanning()

            case CBCentralManagerState.Resetting:
                print("CBCentralManagerState.Resetting")

            case CBCentralManagerState.Unsupported:
                print("CBCentralManagerState.Unsupported")
                break
        }
    }

    // MARK: - Start scanning for StringRay devices with the appropriate UUID
    func startScanning() {
        if let central = centralManager {
            central.scanForPeripheralsWithServices([StingRayGenesisMUUID,StingRayGenesisHRUUID], options: nil)
        }
    }

    // MARK: - CB Central Manager - Did discover peripheral (follows : startScanning)
    func  centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {

        delegate?.bleDidConnectToPeripheral(self, peripheral: peripheral)

        //Check if new discovery and append to BLEDevices where required
        if BLEDevices.contains(peripheral) {
            print("didDiscoverPeripheral - ALREADY DISCOVERED   ==", peripheral.name)
        }
        else{
            BLEDevices.append(peripheral)
            print("didDiscoverPeripheral - NEW DISCOVERY        ==", peripheral.name)
        }
    }

    // MARK:  - CB Central Manager - Connect and Disconnet BLE Devices

    func connectBLEDevice (peripheral: CBPeripheral){
        //Connect
        self.centralManager!.connectPeripheral(peripheral, options: nil)
    }

    func disconnectBLEDevice (peripheral: CBPeripheral){
        //Disconnect
        self.centralManager?.cancelPeripheralConnection(peripheral)
    }



}

委托者

import UIKit
import CoreBluetooth

class MainViewController: UIViewController,UITableViewDelegate,UITableViewDataSource, BLEDelegate {


    //MARK: - View Object Links
    @IBOutlet weak var deviceTableView: UITableView!
    @IBOutlet weak var infoBlockView: UIView!

    // MARK: - Interface Builder Inspectables
    @IBInspectable var BorderWidth : CGFloat = 0.75
    @IBInspectable var BorderRadius : CGFloat = 5.0
    @IBInspectable var BorderColor : UIColor = UIColor.whiteColor()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        formatDeviceTableView()
        formatInFoBlock()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    func bleDidConnectToPeripheral(sender: BLEDiscovery, peripheral: CBPeripheral) {
        print ("Its alive == ", peripheral.name)
    }

    // MARK: - View Fomrating

    func formatInFoBlock(){
        infoBlockView.layer.borderColor = BorderColor.CGColor
        infoBlockView.layer.cornerRadius = BorderRadius
        infoBlockView.layer.borderWidth = BorderWidth
    }


    // MARK: - TableView Functions

    func formatDeviceTableView() {

        deviceTableView.layer.borderColor = BorderColor.CGColor
        deviceTableView.layer.cornerRadius = BorderRadius
        deviceTableView.layer.borderWidth = BorderWidth

    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        //Define a cell and assign it to DeviceTableCellTableViewCell class and use the reuse identifier from IB - "deviceCell"
        let cell = deviceTableView.dequeueReusableCellWithIdentifier("deviceCell") as! DeviceTableCellTableViewCell

        cell.backgroundColor = UIColor.clearColor()
        cell.deviceNameLabel.text = String(indexPath.row)

        return cell

    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("Row Selected ::", indexPath.row)
    }

    func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
        print("Accesory Selected ::", indexPath.row)
    }


}

我希望代码只是打印出“它活着......”,告诉我它正在工作......

1 个答案:

答案 0 :(得分:1)

  1. var delegate: BLEDelegate?;中的委托文件中添加"弱"它:
  2. weak var delegate: BLEDelegate?;

    1. let bleDiscoverySharedInstance = BLEDiscovery();从委托移至委托人。

    2. 完成向viewDidLoad添加:bleDiscoverySharedInstance.delegate = self;,让它知道该代表。

    3. 如果您想要在下面的链接中,您有一个非常类似的例子可以使用代理:https://bitbucket.org/vicrius/flickr-visualizer/src

      希望这一切都有所帮助。

相关问题