4

I have created a model class that I use in my iOS app and my Watch app - it is included in both targets. Now I have to use UIPasteboard in this class which is only available in UIKit, which is not available to watchOS. While I can import UIKit into this file without issue, when I go to use UIPasteboard it will not compile because the watch extension does not know about it.

How can I use UIPasteboard in a class that is available to my watch app?

I wondered if I could only run that code when the device isn't an Apple Watch by using #available, but this didn't resolve the issue.

if #available(iOS 7.0, *) {
    UIPasteboard.generalPasteboard()...
    //ERROR: Use of unresolved identifier 'UIPasteboard'
} else {
    //don't use UIPasteboard
}
Jordan H
  • 52,571
  • 37
  • 201
  • 351

3 Answers3

8

Use the existing preprocessor directive defined in Swift:

#if os(iOS)
//UIKit code here
#elseif os(watchOS)
//Watch code here
#endif

See the documentation for preprocessor directives here.

Léo Natan
  • 56,823
  • 9
  • 150
  • 195
1

Maybe you could use an extension to factor out the UIPasteboard functionality and include the file containing the extension only in the iPhone target.

Ideally, code shared by several OS's should contain only truly shared code.

Also, if you want the conditionality, this is probably a cleaner way to do it.

Community
  • 1
  • 1
Mundi
  • 79,884
  • 17
  • 117
  • 140
1

There are two ways to do so.

First way is using preprocessor directives, like the following example:

#if os(iOS)
    //Insert UIKit (iOS) code here
#elseif os(watchOS)
    //Insert WatchKit (watchOS) code here
#endif

The second way is to determine if the code is called from the WatchKit Extension or iOS App. For example, you can set a global boolean flag to true before calling the code from WatchKit Extension, and false before calling from iOS App. Then the shared code can check the value of the flag to determine it is running on iOS or watchOS.

Seyed Parsa Neshaei
  • 3,470
  • 18
  • 30