Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use UIKit conditionally in file used by Watch app

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
}
like image 643
Jordan H Avatar asked Dec 25 '22 15:12

Jordan H


2 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.

like image 131
Léo Natan Avatar answered Jan 09 '23 04:01

Léo Natan


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.

like image 33
Mundi Avatar answered Jan 09 '23 03:01

Mundi