Jobs Jobs - 5 months ago 21
iOS Question

Protocol not working even after setting the delegate

This is a class where I've defined the protocol. The class I've defined the protocol in is an NSObject(if that makes any difference).

class A:

import UIKit
import CoreBluetooth

protocol deviceNameDelegate {
func discoveredDeviceName(deviceName: String, peripheral: CBPeripheral)
}

class BlueCoreManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
...
var del: deviceNameDelegate?
...
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {

if del != nil {

let peripheralName = peripheral.name!
let peripheralDevice = peripheral
print("Delegate is not nil")
del!.discoveredDeviceName(peripheralName, peripheral: peripheralDevice)

} else {
print("delegate is nil")
}
...
}
}


class B:

import UIKit
import CoreBluetooth

class availableDevicesViewController: UIViewController, deviceNameDelegate {

var ble = BlueCoreManager()
...
override func viewDidLoad() {
super.viewDidLoad()

ble.del = self
}

func discoveredDeviceName(deviceName: String, peripheral: CBPeripheral) {
...
}
}


I've implemented custom protocols twice before but I'm really stumped on this one. I can't seem to figure out why it isn't working. The steps I've followed:

a. I created the protocol blueprint in class A

b. Made an optional delegate variable in class A

c. Passing values at through the delegate in class A

d. Added protocol to class B and implemented function to make it conform to the protocol

e. Set the delegate from class A as self(i.e. class B)

I am still pretty new to swift, so maybe I might have missed something. Can anybody shine a light? What am I not doing?

Answer

Since your BlueCoreManager is a singleton, you shouldn't ever create an instance of it, as you do in your view controller.

You should always use BlueCoreManager.shared() to get the singleton instance.