首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不工作的代表

不工作的代表
EN

Stack Overflow用户
提问于 2016-06-30 13:38:11
回答 1查看 221关注 0票数 0

我正在编写代码来连接到BLE设备,然后将它们列在一个表中以连接或断开它们。我很高兴的外围和管理角色,并了解如何访问BLE设备。在此之前,我使用过NSNotifications,但更愿意使用委托来管理通知。

下面的代码很简单,它扫描设备,然后提示委托,但委托没有响应。

请帮帮我..。

委派

代码语言:javascript
运行
复制
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)
    }



}

委派者

代码语言:javascript
运行
复制
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)
    }


}

我希望代码能打印出“它活着.”向我展示它是有效的..。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-30 13:59:54

  1. var delegate: BLEDelegate?;中的代理文件中添加“弱”:

weak var delegate: BLEDelegate?;

  1. let bleDiscoverySharedInstance = BLEDiscovery();从委托移动到委托方。
  2. 要完成添加:bleDiscoverySharedInstance.delegate = self;到viewDidLoad,让它知道这是委托。

如果您希望在下面的链接中使用委托,可以使用一个非常类似的示例:https://bitbucket.org/vicrius/flickr-visualizer/src

希望这一切都有帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38124805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档