Search code examples
iosobjective-cswiftchromecast

Swift class conforming to Objective-C protocol


In Objective-C I have the the following protocol:

@protocol GCKDeviceScannerListener <NSObject>    
@optional

- (void)deviceDidComeOnline:(GCKDevice *)device;
- (void)deviceDidGoOffline:(GCKDevice *)device;
- (void)deviceDidChange:(GCKDevice *)device;

@end

When trying to conform to this protocol in Swift Xcode 6.1 autocompletes it like this:

class ViewController: UIViewController, GCKDeviceScannerListener {

    override func viewDidLoad() {
        super.viewDidLoad()
        var deviceScanner = GCKDeviceScanner();
        deviceScanner.addListener(self);
        deviceScanner.startScan();
        println("scanning");
    }

    func deviceDidComeOnline(device: GCKDevice!) {
        println("deviceDidComeOnline()");
    }

    func deviceDidGoOffline(device: GCKDevice!) {
        println("deviceDidGoOffline()");
    }

    func deviceDidChange(device: GCKDevice!) {
        println("deviceDidChange()");
    }

}

The code compiles and seemingly runs ok on the simulator. However, none of the listener functions are ever triggered. Everything works 100% of the time when running the demo project from Google written in Objective-C only. Because of the last part I'm assuming that the there aren't any problems with the network or hardware or anything like that.

It could be that I have missed something important from https://developers.google.com/cast/docs/ios_sender, but I would like to know if the Swift code itself is correct according to the protocol. As the protocol only has optional functions it's hard to know if it's right.


Solution

  • I have no experience with this library, but I think you should keep the reference to GCKDeviceScanner.

    Try:

    class ViewController: UIViewController, GCKDeviceScannerListener {
    
        var deviceScanner = GCKDeviceScanner()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            deviceScanner.addListener(self)
            deviceScanner.startScan()
            println("scanning")
        }