WKExtension and ExtensionDelegate

Working working with a SwiftUI Architecture WatchOS app, if you want to use ExtensionDelegate you need to create your own. I have done this, but when I try to actually access the delegate in the code, I am getting the following error message Could not cast value of type SwiftUI.ExtensionDelegate' (0x7fff8441b480) to 'TestMe_WatchKit_Extension.ExtensionDelegate' (0x10c3b36d0).
I have defined the ExtensionDelegate as -

Code Block
class ExtensionDelegate: NSObject, WKExtensionDelegate {
var meetingStatistics: MeetingStatistics = MeetingStatistics()
}

in my @main - I have the following:
Code Block
@main
struct WatchApp: App {
@WKExtensionDelegateAdaptor(ExtensionDelegate.self) var delegate
// code
}

When I try to access the delegate within another class, not via @EnvironmentObject, but via - let delegate = WKExtension.shared().delegate as! ExtensionDelegate I get the above error.

Replies

Well, I tired to get some help on StackOverflow and they didn't get the issue... https://stackoverflow.com/questions/64082376/couldnt-cast-swiftui-extensiondelegate-to-extensiondelegate/64085463#64085463 - Just to be clear, it is not a problem with @environmentObjects - that is working well - passing between the various views... the issue is with passing to a class.

Make sure your ExtensionDelegate conforms to ObservableObject. For example;


Code Block
class ExtensionDelegate: NSObject, ObservableObject, WKExtensionDelegate {
var meetingStatistics: MeetingStatistics = MeetingStatistics()
}

It's mentioned rather quietly in the second init() that the class needs to conform to ObservableObject.

https://developer.apple.com/documentation/swiftui/wkextensiondelegateadaptor