gpt4 book ai didi

swift - 委托(delegate)不工作

转载 作者:行者123 更新时间:2023-11-30 10:01:47 25 4
gpt4 key购买 nike

我正在编写代码来连接到 BLE 设备,然后将它们列在表中以进行连接或断开连接。我对外围设备和管理器角色很满意,并且了解如何访问 BLE 设备。以前我使用过 NSNotifications,但更愿意使用委托(delegate)来管理通知。

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

请帮忙...

委托(delegate)

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)
}



}

委托(delegate)人

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. var delegate: BLEDelegate?; 的委托(delegate)文件中添加“weak”:

弱变量委托(delegate):BLEDelegate?;

  • let bleDiscoverySharedInstance = BLEDiscovery(); 从委托(delegate)移至委托(delegate)者。

  • 要完成添加:bleDiscoverySharedInstance.delegate = self;到viewDidLoad中以让它知道这是委托(delegate)。

  • 如果您想在下面的链接中找到一个非常类似的使用委托(delegate)的示例:https://bitbucket.org/vicrius/flickr-visualizer/src

    希望一切有帮助。

    关于swift - 委托(delegate)不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38124805/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com