I am trying to get this swift protocol to work in an objective c file, but the function is not getting called for some reason. I want the didConnect()
to be called when the device connects and didDisconnect()
to be called when the device disconnects. I set a breakpoint in the centralManager did connect function and printed out delegate
, it came back nil
@objc protocol KestrelDeviceConnectDelegate {
@objc func didConnect()
@objc func didDisconnect()
}
@objcMembers
class KestrelDeviceConnect: NSObject{
static let singleton = KestrelDeviceConnect()
public var delegate: KestrelDeviceConnectDelegate?
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
self.isInitialReading = false
self.kestrelIsConnected = true
kestrelPeripheral.discoverServices(nil)
self.delegate?.didConnect()
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
self.kestrelIsConnected = false
self.delegate?.didDisconnect()
}
}
in the objective c file
@interface ViewController ()<KestrelDeviceConnectDelegate> {
KestrelDeviceConnect<KestrelDeviceConnectDelegate> *_kestrelVC;
}
@implementation ViewController
-(void)viewDidLoad {
[super viewDidLoad];
_kestrelVC = [[KestrelDeviceConnect alloc]init];
[_kestrelVC setDelegate:self];
}
-(void)didConnect{
[[self connectToKestrelButton] setHidden:NO];
}
}
You're very likely creating multiple KestrelDeviceConnect
objects. One has a delegate of ViewController
, and likely there's another that you're actually using for anything.
I suspect you meant this line, which creates a new KestrelDeviceConnect:
_kestrelVC = [[KestrelDeviceConnect alloc]init];
to be this:
_kestrelVC = [KestrelDeviceConnect singleton];