Are you rocking Swift yet? Now is time to share your beautiful code across the whole project for maximum reusability. This becomes even especially essential when creating Apple Watch apps since sharing code between the watch and the phone is a natural occurrence. In this post, I will show you how to create a framework in Swift to do this, which was introduce in Xcode 6.
The Framework
Ok, you got this killer utility class and you’d like to use it in both the iPhone and the Apple Watch. In your project, click on the root of your project, then on top click File > New > Target. In the popup, select iOS > Framework &Â Library > Cocoa Touch Framework:
Next it will ask you for a “Product Name”. This acts as the namespace for the framework so it can be imported as a module in other targets. I like the convention of suffixing my framework libraries with “Kit” like Apple does, so in my case I will call this “UnitKit”:
This will add two areas in your project called “UnitKit” and “UnitKitTests”:
If you’re like me, you might feel filthy that there’s an Objective-C file there, but we won’t really use that and is simply used as a bridge to your framework.
Show Me the Code!
Let’s add a Swift file that represents the code we want to share. I like to create a *Manager file that does heavy lifting for the rest of my project, so in this case I will call it UnitManager. Right-click on your framework and click new file, then add a Swift File:
In this manager class, add anything you like to test it out. Let’s make our class look like this:
public class UnitManager: NSObject { public func getMyStuff(key: String) -> String { return "Here is your \(key)" } }
Notice I am prefixing my class and function with public, otherwise it won’t be accessible from outside of the UnitKit target.
Now go back into your iPhone or Apple Watch target and go to the view controller. After importing the module at the top using “import UnitKit”, Â you can now use your shiny new framework in any target in your project like this:
import WatchKit import Foundation import UnitKit class InterfaceController: WKInterfaceController { override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) var unitManager = UnitManager() var test = unitManager.getMyStuff("test") } }
HAPPY CODING!!
I can not access object from this library to main project. What’s happen to my project? Would you mid help you? Thanks so much !!!
Sure, did you import the namespace in the top of your view controller (or where you’re trying to use it)? Also, remember to make your class, properties, and functions public if you want it to be used from the outside.