Using CocoaPods with Swift

CocoaPods is a dependency manager tool used for mobile application projects, similar to how Composer is used for PHP, and NPM is used for Node.js. Using CocoaPods with Swift projects does not require much work, simply install the CocoaPods gem, add in your dependencies, run the install command and include the packages within your project.

To install the gem, you can run the following command.

$ sudo gem install cocoapods

This will install the cocoapods gem and its dependencies.

Now within your Xcode project, create a Podfile file, this will define your project’s dependencies, similar to how a composer.json file is used in PHP projects.

This can be done by cd‘ing into your project using your computer’s terminal application, and running CocoaPod’s init command.

$ pod init

You should then notice a Podfile has been created. Within this file, you’ll be able to add your dependencies (pods).

For example, to add the GoogleMaps pod to your project, you can include the following markup within your Podfile where [YOUR_PROJECT_NAME] is replaced with your project’s name.

target '[YOUR_PROJECT_NAME]' do
  # Pods for [YOUR_PROJECT_NAME]
  pod 'GoogleMaps'
end

Save the file, and within the same directory, run the pod install command to install the GoogleMaps package.

If this is your first time running the install command, please note that it might take a while to complete as CocoaPods installs its other related libraries.

When the command has finished running, you should see the following output within terminal that looks like the following:

$ pod install
Analyzing dependencies
Downloading dependencies
Installing GoogleMaps (2.3.0)
Generating Pods project
Integrating client project
Sending stats
Pod installation complete! There is 1 dependency from the Podfile and 1 total pod installed.

You may also encounter the following message if your project does not currently have a .xcworkspace file:

[!] Please close any current Xcode sessions and use `[YOUR_PROJECT_NAME].xcworkspace` for this project from now on.

This means that when opening up your project in future, open it via the .xcworkspace file otherwise you may encounter build errors.

Now within your Swift files, you can include the library by using the import keyword at the top of the file, such as within the ViewController.swift file, just underneath the import UIKit declaration.

import UIKit
import GoogleMaps

class ViewController: UIViewController {
}

Another file that gets generated when running pod install is the Podfile.lock file. This file will lock your project down to the specific dependency versions that you have installed. This avoids potential issues of unexpectedly updating dependencies that might not be compatible with your project.

Updated versions of your package dependencies can be updating using the pod update command should you wish to use them within your project.

Note: This article is based on iOS version 10.