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.
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")
}
Apple's documentation on Protocols is long and complex.
It's easiest to think of optional
protocol methods like Optional closures, and you can use it with optional chaining.
@objc class Something {
var delegate: GCKDeviceScannerListener?
func someCallback() {
delegate?.deviceDidComeOnline?(device)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.