How to create XCFramework in swift
In 2019 WWDC, Apple introduced a new format to distribute framework called XCFramework. SDK developers are very excited about this. Following tutorial will help you to learn about creating XCFramework. Let’s get started.
What is a Framework?
Apple Documentation states that a Framework is a hierarchical directory that encapsulates shared resources, such as a dynamic shared library, nib files, image files, localized strings, header files, and reference documentation in a single package. [Source]
As a developer, we often use Apple frameworks like UIKit, AVKit etc.. in our code, these are provided by Apple. We also use third-party frameworks like Google Maps SDK, Facebook SDK etc..
Note: If we want to distribute code without sharing your logic, then we need to distribute it as Framework, else we can distribute as Swift Package manager or Via Cocoa pods.
About XCFramework
A single XCFramework can contain a variant for the simulator, and for the device, also contain a variant for any of the platforms that Xcode supports.XCFrameworks support the binary distribution of Swift and C-based code.
Steps to create XCFramework
- Enable — Build Libraries for Distribution
- Create an archive for every platform using — “Xcode Archive”
- Generate XCFramework using new command — Xcodebuild-Create-XCFramework
Demonstration XCFramework
We are going to create a simple way to save and fetch a string.
- Launch Xcode 11 and above, Create new project -> choose Framework
- Name the project as Storage
- Create a new Swift file and add the below code snippet
Go to build settings -> Search for Build Libraries for Distribution -> change that value to Yes
- Open Terminal and navigate to the Project Directory
- Create an archive for Device architecture using the following command
- If you pass the above two steps without any errors, then you can create XCFramework with the following command [xcodebuild -create-xcframework] [Following command merge Simulator and Device architectures into a single bundle and generates XCFramework]
- Open the -output path, copy the xcframework and paste it in your desired location.
Validate Storage.XCframework within App
- First of all, Create a new Xcode project and choose Single View App
- Under general add Storage.xcframework under framework or libraries
- Add the following code snippet
That’s how we will generate XCFramework and distribute our code without exposing logic. Hope you liked it. Please share your feedback.