Create simple iOS framework using swift

We are going to create simple framework which will provide random UIColor. Post is divided into 3 parts. First part explains creating framework for simulator. Second part explains using framework for simulator. Framework files created for simulator and device are different. In order to create single framework file for both simulator and device, we need to aggregate these files, third part of post explains this process.

1. Creating Framework

Open Xcode and create new project for Cocoa Touch Framework.

Name the framework as FrameworkPOC.

Now add swift file to framework project name it to "RandomColor.swift".

public class RandomColor
{
    public init(){}

    public func fetchRandomUIColor() -> UIColor
    {
        return UIColor(
            red: CGFloat(arc4random_uniform(256)/255),
            green: CGFloat(arc4random_uniform(256)/255),
            blue: CGFloat(arc4random_uniform(256)/155),
            alpha: 1)
    }
}

Copy above code in "RandomColor.swift"

Note: Whatever you want to expose, make it public.

Build app for simulator. Your framework is ready under "Products" directory.

2. Using Framework

Create new Xcode project for single view application. Name it as "UsingFramework".

Now add framework created from the process above to the this project. This is how your general tab should look.

Make sure framework is present under Embedded Binaries and Linked frameworks and Libraries

Lets set view's background color using method provided by framework, update viewController file as follows.

import UIKit
import FrameworkPOC

class ViewController: UIViewController
{
    override func viewDidLoad()
    {
        super.viewDidLoad()

        let objRandomColor: RandomColor =  RandomColor()
        self.view.backgroundColor = objRandomColor.fetchRandomUIColor()
    }
}

Run project on simulator. Re-running will show different color getting set to view.

3. Aggregate Framework

Go to your framework project and add new aggregate target. Name it as "UniversalFrameworkPOC"

Now copy following build script to Run Script section of Build Phases tab.

To create universal framework first run target "FrameworkPOC" and then, "UniversalFrameworkPOC" use device "Generic iOS Device" for both.

After running second target, Finder will open directory containing universal framework.

Previous Post Next Post