Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you selectively import a framework in Swift?

I have a shared framework that needs to be used by iOS and tvOS, but I want to selectively import a framework for iOS only (CoreTelephony). The swift grammar says you can prepend an attribute, but this doesn't work:

@available(iOS 10.0, *) import CoreTelephony

Is this simply not supported? Do I need to subclass just to import the iOS specific framework?

like image 533
Procrastin8 Avatar asked Oct 02 '17 22:10

Procrastin8


People also ask

How do I import a framework?

To embed your frameworks, you shouldn't use the build settings directly, but go to the General tab of the project editor for your app target (select the project item in the navigator, then select the target in the editor pane, then select the General tab). Add your framework under "Embedded Binaries".

How do I add a framework in SwiftUI?

Create new Xcode project using the Framework template Let's begin by creating a framework in Xcode by selecting File > New > Project… from the menu bar. Continue by selecting Framework project template under the iOS tab. Then click Next. Finally name your framework, you can name it whatever you want.

How do I add an Objective-C framework to a Swift project?

To import a set of Objective-C files into Swift code within the same app target, you rely on an Objective-C bridging header file to expose those files to Swift. Xcode offers to create this header when you add a Swift file to an existing Objective-C app, or an Objective-C file to an existing Swift app.

What does import Foundation do in Swift?

You need import SwiftUI if you are writing SwiftUi View s or using other APIs from SwiftUI. You need import Foundation if you are using things like Date or AttributedString or other APIs that aren't a part of the Swift Standard Library or a specialized framework (see below).


Video Answer


1 Answers

For Swift <= 4.0 you can use the os() configuration test function:

#if os(iOS)
  import CoreTelephony
#endif

You'll have to wrap code that uses CoreTelephony as well.

All available tests for os() are: macOS, iOS, watchOS, tvOS, Linux, Windows, and FreeBSD.

For Swift >= 4.1 you can also use canImport():

#if canImport(CoreTelephony)
  import CoreTelephony
#endif
like image 100
Dennis Vennink Avatar answered Oct 16 '22 16:10

Dennis Vennink