frameworks

Xcode: Frameworks

By using frameworks you can share code between multiple projects – a huge productivity boost! In this post you will learn how you can create a framework and how you can use it in your projects.

Hint: This post is using Xcode 8.2.1 and Swift 3.0.2

Creating a Framework

You can simply create a project by using “File -> New -> Project…” and then choosing “Cocoa Touch Framework”:

Xcode creates a project that is configured for creating a framework. As you can see, there isn’t going on a lot in the project:

Now we want to create some functionality. Create a new class and call it “FrameworkExample.swift” and add some functionality:

Important: Classes and functions have to be public, if they should be accessible from another project! In our example, that is the case. Now, choose “Generic iOS Device” and build the project. The framework has been builded. You can find it within the “Products” folder:

You can’t run the framework directly on a device or in a simulator, so that this is not a good way to actually work inside the framework. For that, we have to add the framework to a project.

Adding the framework to a project

In order to have the possibility to both use and change the framework, you can add it to a project. But first, you have to close the Xcode window of the framework project. Then, open the project you want to add the framework to. If the project isn’t a workspace yet, you should save it as a workspace. For that, choose “File -> Save As Workspace”, close the Xcode window and open the “.xworkspace” file. In a workspace file it’s possible to add more than one project.

You can add simply add the framework to the workspace simply by drag and drop: Open a finder window and drag the “.xcodeproj” file to the top position in your project navigator. By doing this, both projects are in your workspace. It should look like this:

In order yo use the framework in your project, you have to add it. For that, click on your project file and go to the “General” tab. You have to add it to the “Embedded Binaries”  by using the “+” button:

It will automatically be added to the “Linked Frameworks and Libraries” section as well:

Now you can import the framework to your source files by using the command  import FrameworkExample. Then, the public API of the framework is available:

Doing it this way, you can add your framework to multiple projects and share the code.

Cocoapods

If you want to provide your framework to a bigger audience or if you want to use a third-party framework, you can can (and should) use Cocoapods. We will discuss the usage of Cocoapods in another blog post – stay tuned!

Video

Resources

Title Image: @ Sinart Creative / shutterstock.com

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.

Amazon