Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKExtension.shared().delegate = self now shows Cannot assign to property: 'delegate' is a get-only property

WatchOS code that used to work for background tasks requires the WKExtention.shared().delegate to be set to self, but now displays an error saying:

Cannot assign to property: 'delegate' is a get-only property

If I remove that line, I don't get updates when background tasks are triggered as I used to be able to receive before.

I have looked up and down StackOverflow and Google and Apple documentation and I can't find an answer. Why that line now shows an error when it used to work just fine.

Make a new WatchKit App and on the InterfaceControllerVC.swift add WKExtensionDelegate to the class and:

    override func awake(withContext context: Any?) {
      super.awake(withContext: context)

      WKExtension.shared().delegate = self
   }

The line:

    WKExtension.shared().delegate = self

is marked red and shows error as:

Cannot assign to property: 'delegate' is a get-only property

like image 413
Ryuuzaki Julio Avatar asked Jun 10 '19 16:06

Ryuuzaki Julio


2 Answers

Not a lot of documentation on how to do this with modern SwiftUI Apps, the Info.plist approach doesn't seem to work anymore. Maybe this will help others to solve this a bit quicker: Use WKExtensionDelegateAdaptor, similar to UIApplicationDelegateAdaptor.

@main
struct WatchApp: App  {

@WKExtensionDelegateAdaptor(ExtensionDelegate.self) var extensionDelegate

@SceneBuilder var body: some Scene {
       
...

}
like image 66
user3074773 Avatar answered Oct 17 '22 16:10

user3074773


The delegate is automatically assigned by the system as it is described here.

Apple Doc WKExtensionDelegate

Setting your delegate object by doing the followings:

  1. Create a class with name Your_Class_ExtensionDelegate and implements the protocol WKExtensionDelegate.
  2. Make sure the value of WKExtensionDelegateClassName in Info.plist in WatchKit Extension is $(PRODUCT_MODULE_NAME).Your_Class_ExtensionDelegate (Module name is necessary for Swift projects.)
like image 38
Evan Avatar answered Oct 17 '22 16:10

Evan