Is there any way to conditionally import a framework in Swift
based on runtime iOS version?
In particular, I have an app with a deployment target of iOS 8
. I would like to use the new Apple Speech
framework in the app, if it is available at runtime. I am aware of the #available(iOS 10, *)
directive for code sections, and the @available(iOS 10, *)
directive which can be used for an entire class. So I can easily avoid executing any code that uses the Speech framework with those. But in the file that contains the class that uses Speech, I need the "import Speech" statement, and neither of those two directives can be used there. I am finding that even if I have the @available(iOS 10, *)
directive on my entire class, when I run my app on an iOS 9 device it is killed at launch with
"dyld: Library not loaded: /System/Library/Frameworks/Speech.framework/Speech".
Am I missing something, or is it only possible to use the Speech framework in an app that has deployment target of 10?
The correct approach is as follows: Import your Objective C framework by dragging and dropping the framework into an Xcode 6 Swift project. Create a new Objective C file in your project (File->New->File [Objective C for iOS]). Accept the prompt (agree) to create a bridging header file between Objective C and Swift.
In Swift parlance, a module is a compiled group of code distributed together. A framework is one type of module while an app is another. Note: If you want to learn more about frameworks, read What are Frameworks?.
You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.
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.
You can make the Framework optional (details and image from Ray Wenderlicht):
This, combined with your use of @available, should prevent the system from trying to load it on the devices where it is not available.
You need to use
#if canImport(YourFramework) import YourFramework #endif
instead of @available now, after setting your framework as optional :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With