Use UIKit conditionally in the file used by the Watch application

I created a model class that I use in my iOS application and Watch application - it is included for both purposes. Now I have to use UIPasteboard in this class, which is only available in UIKit , which is not available for watchOS. Although I can import UIKit into this file without problems, when I go to use UIPasteboard , it will not be compiled because the chat extension does not know about it.

How can I use UIPasteboard in a class available for my watch app?

I was wondering if I can run this code only when the device is not an Apple Watch using #available , but this did not solve the problem.

 if #available(iOS 7.0, *) { UIPasteboard.generalPasteboard()... //ERROR: Use of unresolved identifier 'UIPasteboard' } else { //don't use UIPasteboard } 
+4
source share
3 answers

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 .

+5
source

There are two ways to do this.

The first way is to use preprocessor directives, for example, 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 application or iOS. For example, you can set the global boolean flag true before calling the code from WatchKit Extension and false before calling from the iOS application. The generic code can then check the value of the flag to determine if it works on iOS or watchOS.

+1
source

Perhaps you could use the extension to share the functionality of UIPasteboard and include the file containing the extension only on the target iPhone.

Ideally, code shared by multiple operating systems should contain only truly generic code.

Also, if you want conditions to be, this is probably a cleaner way to do this.

0
source

All Articles