Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reference a Swift class in my WatchKit extension from the core iOS code?

I am trying to make my iOS application send the WatchKit Extension a set of data each time that data is updated from the server.

This is what the code in my iOS app looks like (names changed)

[WatchKitDataModel loadDataFromSource: currentData]

However, the iOS application does not recognize the WatchKitDataModel.

The error is "use of undeclared modifier."

Please help me make my apps talk to one another!

like image 622
Konstantin Gizdarski Avatar asked Dec 26 '22 00:12

Konstantin Gizdarski


2 Answers

Ensure that your offending class is added to both the App target and the WatchKit target in the Document panel

enter image description here

The picture shows a TodayExtension but the principle is the same.

like image 189
Warren Burton Avatar answered Dec 28 '22 10:12

Warren Burton


To share code between your WatchKit Extension and its containing app, create an embedded Framework in your app. Frameworks are the recommended tool by Apple to share code, within an app, and between apps.

To create an embedded Framework in Xcode 6, select your project and go to File > New > Target... Then in the dialog that opens select iOS > Framework & Library > Cocoa Touch Framework. Click Next. Give it a name, SomethingKit, similar to what Apple uses, e.g. UIKit, HealthKit, WatchKit. Now create your new classes and other common code in files inside your new Framework. When you want to use it in any of your other targets, i.e. the WatchKit Extension or its containing app, don't forget to import SomethingKit.

Ah, and don't forget to give public access level to the public-facing classes and functions in your Framework.

For more information about Frameworks to share code, for example, what sort of things cannot be included in Frameworks, see Apple's article: Using an Embedded Framework to Share Code.

There is also an interesting WWDC 2014 session video about this: Building Modern Frameworks.

like image 23
alondono Avatar answered Dec 28 '22 08:12

alondono