Sharing Utilities Using CocoaPods Subspecs

 ·  iOS, Development  ·  Tagged CocoaPods, Subspecs, TWTToast, Sharing and Utilities

In mid-January, we published TWTToast, a project that collects various utility classes and categories we’ve written over the years. While it’s interesting and useful, we’ll save highlighting its modules for another day. In today’s post, we’re going to focus on how it’s packaged.

Until recently, we didn’t have a good way to share lots of small, unrelated utility modules. Packaging them as a monolithic library is bad for users who only need to include a few modules. GitHub Gists granularly organize the modules, but also make them hard to find. Creating a git submodule for each utility module would almost work, but managing so many repositories would be very tedious.

Our ideal solution for organizing and sharing utilities meets three criteria:

  1. Users are able to easily include only the modules they need.
  2. Code is available in a central repository that all our team members can easily find, use, and contribute to.
  3. Adding and maintaining modules fits into our current development and review processes.

CocoaPods subspecs fulfill all three of these.

CocoaPods Subspecs

CocoaPods is the de-facto standard for distributing libraries in the Cocoa community, but few know about subspecs. Subspecs allow pod authors to break their podspecs into discrete chunks, each of which can be added to a Podfile like any other pod. This allows a library’s users to include only the parts they need, while its developers can treat it as a single project.

With TWTToast, each utility module—typically a header and implementation file—has an associated subspec in our podspec. For example, the snippet below defines our UIKit subspec, which has two sub-subspecs: AutoLayout and Color.

## Subspec for Files Related to UIKit
s.subspec 'UIKit' do |ss|
  ss.subspec 'AutoLayout' do |sss|
    sss.source_files = "UIKit/Auto Layout/*.{h,m}"

  ss.subspec 'Color' do |sss|
    sss.source_files = "UIKit/Color/*.{h,m}"


If you only want our Color module, you can get it by adding the following line to your Podfile,

pod 'TWTToast/UIKit/Color'

None of our other utilities are included in your project. You can specify any combination of modules this way.

We’ve found that this approach works very well for everyone. Module users get easy-to-use, à la carte module inclusion, and we can store all our utilities in a single repository on GitHub, where it fits in with our existing development processes. This makes it easy for us to add and share new modules.

Next time you’re thinking about publishing your utility classes and categories, consider distributing them using CocoaPods subspecs. We think they’re a great, low-overhead way to organize and share utilities with the Cocoa community. Also, go have a look at TWTToast! We’ve got several useful utilities in there now, and we’ll be adding more soon!