How to Create a CocoaPod in Swift

How to Create a CocoaPod in Swift
Learn how to make your own CocoaPod!

Learn how to make your own CocoaPod in this ice-cream-delicious tutorial!

You’re probably familiar with some well-known, open-source CocoaPods such as Alamofire or MBProgressHUD. But sometimes you can’t find a a pod with the exact functionality you need, or you may want to separate a large project into smaller, reusable components.

Fortunately, it’s easy to create your own CocoaPods!

If you’ve already created a Cocoa Touch framework for your component, you’ve already done most of the hard work. If you haven’t, don’t panic as it’s really straightforward.

If you’ve only ever created classes as part of an iOS app, that’s okay too. You can easily create a new pod by pulling out classes and functionality that make sense for your particular use case.

This tutorial picks up where How to Use CocoaPods with Swift ends. If you’ve never used CocoaPods before, then that tutorial is definitely a prerequisite to this one.

Otherwise, grab yourself a hot cup of “cocoa” (sorry, couldn’t resist!) and read on! :]

Getting Started

Your top client is Ice Cream Shop, Inc. Their ice cream is so popular they can’t keep up with customer orders at the counter. They’ve recruited you to create a sleek iOS app that will allow customers to order ice cream right from their phone. You’ve started developing the app, and it’s coming along well.

Download the starter project from here — this is the final project from How to Use CocoaPods with Swift.

The app has a few pod dependencies that are already included in the download, so you don’t need to run pod install to install them.

Note: If you worked through How to Use CocoaPods with Swift this next section may seem familiar – it’s simply a review of that tutorial. Feel free to skip ahead as needed.

Open IceCreamShop.xcworkspace and then Main.storyboard, found in the Views\Storyboards & Nibsgroup, to see how the app is laid out.

Here’s a quick overview of the Choose Your Flavor scene, which is the heart of the application:

  • PickFlavorViewController: handles user interaction, such as when the user selects an ice cream flavor.
  • PickFlavorDataSource: is the data source for the collection view that displays ice cream flavors.
  • IceCreamView: is a custom view that displays an ice cream cone and is backed by a Flavor model.
  • ScoopCell: is a custom collection view cell that contains a ScoopView, which is also backed by an instance of the Flavor model class.

Storyboard Annotated

The top managers at Ice Cream Shop really like how the app is coming along, but they’ve added a new requirement: ice cream retailers need to have the same choose-your-own-flavor functionality in their apps.

Wait, that wasn’t in the original design. But that should be no probelm for a super developer like you!


Can you guess how you’re going to do this? Yep, you’re going to pull this functionality into its own CocoaPod!

Setting up Your Pod

Create a new Xcode project and select iOS\Framework & Library\Cocoa Touch Framework, and then click Next:

Create Cocoa Touch Framework

Enter RWPickFlavor for the product name and Swift for the language. Click Next.

For the purposes of this tutorial you will create the project in ~/Documents/Libraries. Choose the Documents folder in your home directory. If you don’t already have a Libraries folder, click on the New Folder button in the bottom and create it.

Finally, choose the Libraries folder and click Create.

The directory where you save your development pods is important because you will need to reference this directory from your Podfile during local development.

Normally, when you use CocoaPods, you include dependencies in your Podfile like this:

pod 'PodName', '~> 1.0'

But when you’re developing your own CocoaPod, you will instead specify a local path, like this:

pod 'MyPodName', :path => '~/Path/To/Folder/Containing/My/Pod'

There are two benefits to this approach:

  1. It uses the local files on your machine for the pod, instead of fetching them from a remote repository.
  2. Normally, you don’t make changes to a pod included by your app because those changes would be overwritten the next time you run pod install, as the pod will be re-fetched from the remote repository and the source files you changed would be overwritten. By using the :path => syntax, you can easily make changes to the pod during development that won’t be overwritten, since the specified path is now the source of the CocoaPod, and thus your changes won’t be lost when you run pod install again.

While you can use a different location for your development pods, in general I recommend putting them in ~/Documents/Libraries. This is also a good location if you work with a team of developers since CocoaPods knows to expand the tilde as the user’s home directory; therefore you don’t need to hard code an absolute path in the Podfile to this directory.

You can also use other CocoaPods within your project as dependencies for the CocoaPod you created — you simply need a Podfile to manage your CocoaPod’s dependencies.

Close Xcode, then enter the following commands in Terminal:

cd ~/Documents/Libraries/RWPickFlavor
pod init
open -a Xcode Podfile

This creates a new Podfile and opens it in Xcode.

Replace the entire contents of the new Podfile with the following:

platform :ios, '8.0'
target 'RWPickFlavor' do
  pod 'Alamofire', '~> 1.2'
  pod 'MBProgressHUD', '~> 0.9.0'

This declares that RWPickFlavor will have external dependencies on both Alamofire and MBProgressHUD.

Save and close the Podfile, then enter the following command in Terminal:

pod install

Just as you’d expect, this creates a workspace and installs the various requisite files.

Note: If pod install gives you any warnings, then you’re likely using an older version of CocoaPods. Swift based CocoaPods, such as Alamofire, require CocoaPods version 0.36.0 or newer. You can check the version of CocoaPods you have installed by running the following command in Terminal:

pod --version

If that’s the case, enter the following in Terminal to install the latest version of CocoaPods:

sudo gem install CocoaPods

Enter the following command in Terminal to open the newly created RWPickFlavor workspace:

open RWPickflavor.xcworkspace

Your project navigator should now look like the following:

RWPickFlavor New Pod Files Hierarchy

You now need to copy a few of the existing files from the IceCreamShop workspace into RWPickFlavor.

First, create the following groups in RWPickFlavor.xcworkspace to hold the files you’re going to copy:

  • Categories
  • Controllers
  • Factories
  • Models
  • Views
    • Ice Cream
    • Storyboards & Nibs

Now drag and drop everything — except for AppDelegate.swift and LaunchScreen.xib — from the above groups in IceCreamShop.xcworkspace into the corresponding groups in RWPickFlavor.xcworkspace like so:

Copy Workspace Files

When prompted, ensure that Copy items if needed is checked so that each file will actually be copied instead of simply linked.

When you’re done, RWPickFlavor should have the following files:

  • RWPickFlavor
    • RWPickFlavor.h
      • Categories
        • RGBAColorFromString.swift
      • Controllers
        • PickFlavorDataSource.swift
        • PickFlavorViewController.swift
      • Factories
        • FlavorFactory.swift
      • Models
        • Flavor.swift
      • Supporting Files
        • Info.plist
      • Views
      • Ice Cream
        • IceCreamView.swift
        • ScoopCell.swift
        • ScoopView.swift
      • Storyboard & Nibs
        • Main.storyboard

Once you’re sure all the files have been copied over, delete the originals and any empty groups from IceCreamShop, leaving just the files in RWPickFlavor. Take care not to delete any of the following:

  • AppDelegate.swift
  • LaunchScreen.xib
  • Images.xcassets
  • Anything under the Supporting Files group

Now open Info.plist, found under the Supporting Files group, and delete the line for Main storyboard file base name.

Build and run. You shouldn’t see any errors, and you’ll eventually see the “Ice Cream Shop” logo followed by a black screen.

What About the Images?

You may have noticed that you didn’t copy over the Resources group; this is because you need to copy just background.jpg itself into the Resources folder of RWPickFlavor — not the complete Images.xcassets file.

First, create a new Resources group within RWPickFlavor.

Next, select Images.xcassets in IceCreamShop, right click on background and select Show In Finder, like so:

Background Show In Finder

Now drag and drop background.jpg from Finder into the Resources group in RWPickFlavor. Again, make sure that you check Copy items if needed when prompted. After you’ve copied the image, delete the original background from Images.xcassets in IceCreamShop.

Finally, in RWPickFlavor update the image view’s image on the Choose Your Flavor scene in Main.storyboard so that it refers to background.jpg instead of simply background:

Update PickFlavorViewController Image View Image

Believe it or not, the hardest part of creating your pod is done! :]

High Five!

CocoaPods and Git

Since CocoaPods is bootstrapped on top of Git, each pod will need to have its own Git repository. If you already have a preferred Git host, great — you can use it to host your repository.

If you don’t, GitHub is an excellent choice as it’s well-known by developers and has a free plan for open-source projects.

Bitbucket is another great option as it has a free unlimited tier, including private repositories, for teams of up to five developers.

This tutorial uses GitHub, but feel free to use your preferred Git host instead.

GitHub Repo Setup

First, Sign up or Login to your GitHub account.

Next, click on the + (create new) icon on the top right of the screen and select New repository as shown below:
Github: New Repository

Enter RWPickFlavor for the Repository name, and select Create repository.

Github will create a new repository under your account; you’ll then see the following screen with a Quick setup section that displays your repository URL:

Github Quick Setup

You’ll need this URL in just a moment, so leave the page open for now.

Now you need a second repository to host all of your private pod specs — you’ll use this later on in the tutorial.

Open in a new tab; again, press the Create new icon and select New repository. Name this repository RWPodSpecs, and select Create repository.

Leave this tab open as well so you can easily grab the URL later when you need it.

Podspec Setup

Now you need to create the RWPickFlavor.podspec file for RWPickFlavor. The Podspec includes basic information such as the pod’s name, version and Git download URL.

Enter the following commands in Terminal, hitting enter after each one:

cd ~/Documents/Libraries/RWPickFlavor
pod spec create RWPickFlavor
open -a Xcode RWPickFlavor.podspec

This creates RWPickFlavor.podspec and opens it in Xcode.

There’s a lot of excellent documentation and examples in the default Podspec – however, you don’t need most of it.

Replace everything in RWPickFlavor.podspec with the following: do |s|
  # 1
  s.platform = :ios
  s.ios.deployment_target = '8.0' = "RWPickFlavor"
  s.summary = "RWPickFlavor lets a user select an ice cream flavor."
  s.requires_arc = true
  # 2
  s.version = "0.1.0"
  # 3
  s.license = { :type => "MIT", :file => "LICENSE" }
  # 4 - Replace with your name and e-mail address = { "[Your Name Goes Here]" => "[]" }
  # For example,
  # = { "Joshua Greene" => "" }
  # 5 - Replace this URL with your own Github page's URL (from the address bar)
  s.homepage = "[Your RWPickFlavor Homepage URL Goes Here]"
  # For example,
  # s.homepage = ""
  # 6 - Replace this URL with your own Git URL from "Quick Setup"
  s.source = { :git => "[Your RWPickFlavor Git URL Goes Here]", :tag => "#{s.version}"}
  # For example,
  # s.source = { :git => "", :tag => "#{s.version}"}
  # 7
  s.framework = "UIKit"
  s.dependency 'Alamofire', '~> 1.1'
  s.dependency 'MBProgressHUD', '~> 0.9.0'
  # 8
  s.source_files = "RWPickFlavor/**/*.{swift}"
  # 9
  s.resources = "RWPickFlavor/**/*.{png,jpeg,jpg,storyboard,xib}"

Just like a Podfile, the Podspec is written in Ruby. Be extra careful not to make any typos, or else the pod will likely fail to validate and/or install later.

Here’s what’s going on:

  1. You first specify basic information about the pod. Swift based CocoaPods must have a minimum deployment target of 8.0 or higher. If you specify a lower version, the pod won’t install correctly.
  2. A Podspec is essentially a snapshot in time of your CocoaPod as denoted by a version number. When you update a pod, you will also need to update the Podspec’s version. All CocoaPods are highly encouraged to follow Semantic Versioning. If you’re not familiar with Semantic Versioning, see How to Use CocoaPods with Swift for more information.
  3. All pods must specify a license. If you don’t, CocoaPods will present a warning when you try to install the pod, and you won’t be able to upload it to CocoaPods trunk – the master specs repo.
  4. Here you specify information about yourself, the pod author. Enter your name and e-mail address instead of the placeholder text.
  5. Here you need to specify the URL for your pod’s homepage. It’s okay to simply copy and paste the Github homepage from your browser’s address bar to use here.
  6. Replace this URL with the Git download URL from the “Quick Setup” section of the first repo you created above. In general, it’s best to use either a http: or https: URL to make it easier for other users to consume. You can use an SSH URL if you want, but you’ll need to make sure that everyone on your team — and whoever else needs access to the CocoaPod — already has their public/private key pairs setup with your Git host.
  7. Here you specify the framework and any pod dependencies.
  8. Here you specify the public source files based on file extensions; in this case, you specify .swift as the extension.
  9. Finally, you specify the resources based on their file extensions.

Like every other pod, you’ll need to create the LICENSE file.

Copy and paste the MIT License found here into your favorite text editor, and then save the file as LICENSE – with no extension – in ~/Documents/Libraries/RWPickFlavor. Make sure to replace [year] and [fullname] with the actual values- uh, the year and your actual name, of course. ;]

Choose a License is a really great site that helps you choose the most appropriate open-source license for your project, and is built and maintained by the good folks at GitHub.

Push to Git

You’re finally ready to push the RWPickFlavor pod to its new home on GitHub!

Enter the following commands in Terminal, replacing [Your RWPickFlavor Git URL] with the Git URL for RWPickFlavor repo you created earlier:

cd ~/Documents/Libraries/RWPickFlavor
git init
git add .
git commit -m "Initial commit"
git tag 0.1.0
git remote add origin [Your RWPickFlavor Git URL]
git push -u origin master --tags

If prompted, enter your username and password for Github.

This commits all of the files within the RWPickFlavor directory, creates a new 0.1.0 tag, and pushes eveything to your remote repository.

Congratulations, you’ve just created your first CocoaPod!

Victory Dance!

You’ve created your first CocoaPod, but can you actually use it? Well, not quite yet. :]

You first need to add your Podspec to a private specs repo; this lets CocoaPods find the pod when you try to install it. Fortunately, you’ve already created a Git repo for this, so this final step is relatively straightforward.

Enter the following in Terminal, making sure you’re still in the RWPickFlavor directory:

pod repo add RWPodSpecs [Your RWPodSpecs Git URL]
pod repo push RWPodSpecs RWPickFlavor.podspec

Make sure to replace [Your RWPodSpecs Git URL] with the Git URL for RWPodSpecs repo you created earlier.

This creates a local reference to RWPodSpecs that’s stored in ~/.cocoapods on your machine, and pushes the RWPickFlavor.podspec to it.

You now have a private pod specs repo set up! Easier than you thought, right?

Using Your New CocoaPod

It’s finally time to use your newly created pod.

Open the Podfile for IceCreamShop and replace its contents with the following:

platform :ios, '8.0'
source ''
source '[Your RWPodSpecs Git URL Goes Here]'
target 'IceCreamShop' do
  pod 'RWPickFlavor', :path => '~/Documents/Libraries/RWPickFlavor'

Make sure that you replace [Your RWPodSpecs Git URL Goes Here] with the Git URL for your RWPodSpecs repo.

Then, run pod install in Terminal.

Finally, replace the entire contents of AppDelegate.swift with the following:

import UIKit
import RWPickFlavor
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  var rootViewController: UIViewController!
  func application(application: UIApplication, didFinishLaunchingWithOptions 
    launchOptions: [NSObject : AnyObject]?) -> Bool {
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window?.rootViewController = rootViewController
    return true
  func setupRootViewController() {
    let bundle = NSBundle(forClass: PickFlavorViewController.self)
    let storyboard = UIStoryboard(name: "Main", bundle: bundle)
    rootViewController = storyboard.instantiateInitialViewController() as! UIViewController

In setupRootViewController(), you get a reference to the RWPickFlavor “bundle” – which is actually a dynamic framework – create a reference to the Main.storyboard, and instantiate its root view controller.

Build and run. You’ll be greeted with the familiar “Choose Your Flavor” screen. Awesome! :]


Abstracting All The Things!

If you’re like me, you’re probably thinking, “Wow, App Delegate sure knows a lot about the structure of RWPickFlavor!”

Fortunately, there’s something you can do to reduce this tight-coupling: use BetterBaseClasses – a CocoaPod that makes creating other CocoaPods easier.

Add the following code to the pod file for RWPickFlavor, right after the line for Alamofire:

pod 'BetterBaseClasses', '~> 1.0'

Likewise, add the following to RWPickFlavor.podspec, right below the line for Alamofire:

s.dependency 'BetterBaseClasses', '~> 1.0'

Now replace the s.version line with the following:

s.version = "0.2.0"

Here you’re declaring BetterBaseClasses as a dependency, and then bumping the version of your CocoaPod.

Now run pod install in Terminal to install this new dependency.

Next, add the following import to PickFlavorViewController, again right after the line for Alamofire:

import BetterBaseClasses

Then replace the class definition with the following:

public class PickFlavorViewController: BaseViewController, UICollectionViewDelegate {

This changes PickFlavorViewController so it inherits from BaseViewController, which is part of BetterBaseClasses.

Now you need to push these changes to both your RWPickFlavor and RWPodSpecs repositories. Run the following commands in Terminal:

cd ~/Documents/Libraries/RWPickFlavor
git add .
git commit -m "Added BetterBaseClasses dependency"
git tag 0.2.0
git push origin master --tags
pod repo push RWPodSpecs RWPickFlavor.podspec

Next, you need to pull this change into IceCreamShop.

Update the Podfile for IceCreamShop by replacing the pod 'RWPickFlavor' line with the following:

pod 'RWPickFlavor', '~> 0.2.0'

Here you’re updating the Podfile to request the version of RWPickFlavor you just pushed.

Then execute pod install in Terminal to update this dependency in IceCreamShop.

Lastly, replace the entire contents of AppDelegate.swift with the following:

import UIKit
import RWPickFlavor
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  func application(application: UIApplication, didFinishLaunchingWithOptions 
    launchOptions: [NSObject : AnyObject]?) -> Bool {
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window?.rootViewController = UINavigationController(rootViewController: 
    return true

That’s much simpler!

BetterBaseClasses adds categories to UIViewController, UITableViewController, and other UIkit classes. This includes a category called UIViewController+BetterBaseClasses, which adds convenience methods such as instanceFromStoryboard() to make it super easy to instantiate view controllers, whether they live in the main bundle or somewhere else, such as a framework in this case.

Build and run. Once again, you should be greeted with the familiar “Choose Your Flavor” screen.

Where to Go From Here?

You can download the completed IceCreamShop project here, and the RWPickFlavor pod here.

You’re now ready to start making your own CocoaPods! However, what you’ve covered in this tutorial is really just the tip of the iceberg when it comes to CocoaPods. Check out the CocoaPods Guides to learn everything you need to know about creating CocoaPods.

After you create a CocoaPod, you might consider adding it to the CocoaPods Master Specs Repo so that it will be made available via to thousands of developers around the world. Refer to the CocoaPods Trunk blog post to find out how you can do this!

If you have any questions or comments about the tutorial, feel free to join the discussion in the comments below!

How to Create a CocoaPod in Swift is a post from: Ray Wenderlich

The post How to Create a CocoaPod in Swift appeared first on Ray Wenderlich.



Write a comment