There is a lot of discussion about Cocoapods recently. You may have heard it from other developers, or you can see it in the GitHub directory. If you've never used it before, you might ask, "What the hell is Cocoapods?" "
It's not the mysterious Amazon area where the tribes are picking out the cocoa pods with their hands, certainly not! It may be best for Cocoapods website to answer:
Cocoapods is a dependency management tool for cocoa projects. It has thousands of libraries that can help you to expand your project gracefully.
Extending a project gracefully sounds curious, but what is a dependency management tool? Why would you need it?
No matter what kind of app you're creating, you're likely to use other developer code, either in the form of a frame or in the form of a library. You may be familiar with Uikit and foundation, both of which are the framework offered by Apple.
In this tutorial, you will:
Find out why you're making friends with third-party libraries
Installing Cocoapods
Using Cocoapods in a starter project
Install use and modify dependency files to improve the user experience
Understanding Semantic Version Control
Why is the library your friend?
While you don't necessarily have to use third-party libraries and frameworks, they do save you a lot of time, allowing you to focus on optimizing your app rather than hitting countless lines of code that you don't need to write.
You can use third-party libraries and frameworks without relying on management tools, and our website provides a practical tutorial on how to use them. For example, this is our Alamofire tutorial and Swiftyjson Tutorial.
Without the use of dependency management tools, you can simply add each library to your project manually by hand. However, this approach has several drawbacks:
Updating a library to a new version can be cumbersome, especially if a library relies on another library, so you must update all of the libraries.
Adding a three-party library to your project might require some local modifications in your code, which makes it more difficult to update the version later.
Judging the current version of the library used in your app is also difficult, especially if you haven't recorded it in advance.
Finding a new library is difficult if you don't have a central location to see all the available libraries.
Cocoapods help you overcome these problems and more. It captures library code, solves dependencies between libraries, helps you find and discover new libraries, and even configures the right environment for your project in the simplest way.
Premise
This tutorial requires you to familiarize yourself with the basics of iOS and swift development. If you don't know anything about iOS or Swift, before you look at this tutorial, you'd better look at some of the other articles or video tutorials on our site and then come back to this article. Or go deep into learning iOS apprentice.
This tutorial also contains classes that use the core graphics. Understanding the core graphics is a good thing, but not a must. If you want to learn more about Core graphics, please read our modern core graphics with Swift series.
This tutorial requires Xcode 6.3 and Swift 1.2.
Begin
First you need to install Cocoapods. Fortunately, Cocoapods is built on Ruby, and the latest version of Mac OS X comes with Ruby. This has been done since OS X 10.7.
Open the terminal and enter the following command line:
1 |
sudo gem install cocoapods |
Enter your password when requested. The output of the terminal should look like this:
You must use sudo to install cocoapods, but you will not need to use it after installation.
Finally, enter the following command line at the terminal to complete the setup:
This process may take a few minutes, as it clones the Cocoapods Master Specs repository into the ~/.cocoapods/directory on your computer.
The verbose option records the progress of the process as it progresses, allowing you to see the process instead of a zombie screen.
Great, now you're starting to set up to use Cocoapods.
Code time!
Developed an app for customer Ice Cream Shop, Inc.
Your top customer is the ice Cream Shop, Inc. Their ice cream was so popular that they could not receive the orders from the customers at the counter. They hire you to make a beautiful iOS app that allows users to order on their iphone.
You've started to develop apps, and you've made good progress. Download the Start program here.
Open the Icecreamshop.xcodeproj and run and you'll see a very tasty vanilla ice cream.
The user should be able to choose the flavor of the ice cream from this screen, but it is not possible because you have not finished this function yet.
Open Main.storyboard from Views/storyboards&nibs to see the layout of the app. Now let's take a quick look at the core of the app, the "Choose Your Taste" screen:
Pickflavorviewcontroller handles user interaction, for example, when a user chooses a taste of ice cream.
Pickflavordatasource is a data source for different flavors of ice cream that collection view shows.
Icecreamview is a custom view that can be used to showcase ice cream cone-shaped omelets, and it is supported by the flavor model.
Scoopcell is a custom Collectionviewcell that contains a scoopview, which is supported by the flavor model.
Since each ice cream shop will have some signature flavors, each has its own local flavour. Therefore, the data contained in the flavor instance needs to be provided through a Web service.
However, this has not answered the question, "Why can't users choose an ice cream flavor?" "
Under Controllers this group, open Pickflavorviewcontroller.swift, and you'll see an alternate method:
12 |
private func loadFlavors() { // Implement this} |
Haha, there is no taste in this, you need to implement it.
You can use Nsurlconnection or nsurlsession and write your own network class, here is a more simple way: Alamofire, an open source network library.
You might want to just download it and drag the file to the project. However, that is a very troublesome way. Cocoapods provides a more elegant and flexible solution.
So, gossip less ...
Install your first dependency management tool
First you have to turn off Xcode.
Yes, you're right, it's time to create a podfile, where you define project dependency management.
Open the terminal and use the CD command to enter the directory containing your Icecreamshop project:
1 |
cd ~/Path/To/Folder/Containing/IceCreamShop |
Next, enter the following command:
This will create a podfile for your project
Enter the following command line to open Podfile and edit with Xcode:
Note: You cannot use TextEdit to edit podfile, as it is possible to replace standard quotes with a graphical, more attractive typeset quotes, which may cause cocoapods to fail to understand and throw an error, So it's best to use Xcode or another programming text editor to edit your podfile.
The default podfile looks like this:
12345 |
# Uncomment this line to define a global platform for your project# platform :ios, ‘6.0‘ target ‘IceCreamShop‘ do end target ‘IceCreamShopTests‘ do end |
Replace the contents of the comment with the following two lines:
1 |
platform :ios, "8.0" use_frameworks! |
This tells cocoapods--that your project is using iOS 8.0 and that the framework will be used instead of the static library.
To use Cocoapods in Swift, you must explicitly write use_frameworks! To select the use frame. If you forget to write this, CocoaPods can detect that you are using Swift CocoaPods, you will get an error when installing pods.
If you've only used swift programming, it might seem odd-that's because Podfiel actually wrote it in Ruby. You don't need to learn ruby in order to use Cocoapods, but you know that even small text errors often cause cocoapods to go wrong.
About "Libraries"
You will see that the "library" usually refers to libraries or frameworks. I'm sorry this tutorial has inadvertently mixed up these two concepts. In fact, when someone mentions "Swift library", they actually refer to "swift dynamic frameworks" because Swift does not allow static libraries.
You might want to know the difference between the library and the Framework (FRAMEWORKD) and the cocoapod.
Cocoapod or shorthand for "pod" is a common term used to indicate the use of cocoapods tools to add libraries or frameworks to your application.
IOS 8 introduces a dynamic framework that allows code, pictures, and other things (assets) to be packaged together. Prior to iOS 8, Cocoapods was created as a static library, which is a "bloated" binary file. This means that it contains some code description settings (such as i386 for the simulator, ARMV7 for devices, etc.), but they are not allowed to contain any resources, examples, or assets.
Another important difference is that the dynamic framework has a namespace class, while the static library does not. So, if there is a class in a different static library in a single project called Mytestclasses, then Xcode may not be able to successfully create the project because it will fail because of duplicate identities. However, Xcode is happy to have a class with the same name in each of the different frameworks in a project.
Why is this important? Unlike OC, the standard Swift Runtime library (runtime libraries) is not included in iOS! This means that your framework must contain the necessary swift run-time libraries. Therefore, pods written in swift language must be created in a dynamic framework. If Apple allows swift static libraries, duplicate symbols will be generated in different libraries that use the same standard runtime dependency.
Fortunately, Cocoapods did these things for you. It can even do a one-time inclusion of the required dependencies. All you have to do is to remember to include use_frameworks! in Podfile when using Swift Cocoapods , then there is no problem.
Amazing, right?
Install your first dependency
This is the last moment to install your dependency file using Cocoapods. Add the following content to your Podfile
1 |
pod ‘Alamofire‘ , ‘1.2.3‘ |
This is telling cocoapods you want to add 1.1.4 version of Alamofire to your project as a dependency file, which is the latest version when writing this tutorial.
Save and close Podfile
Now you need to tell Cocoapods to install the dependency file for your project. Enter the following command in the terminal, but first make sure you are still in the directory containing the Icecreamshop and Podfile:
You will see that the output is similar to the following
12345 |
Analyzing dependencies Downloading dependencies Installing Alamofire (1.1.4)Generating Pods project Integrating client project [!] Please close any current Xcode sessions and use `IceCreamShop.xcworkspace` for this project from now on. |
Using the Finder to open your project folder, you can see that Cocoapods created a new Icecreamshop.xcworkspace file and a pods file to store all of the project dependent files.
Note: From now on, like a command-line warning prompt, you must use the workspace file instead of project, or you will experience a compilation error.
That's great! You have added your first dependency management using Cocoapods.
Use the installed Pods
If you have already opened the Xcode project, close it and open icecream.xcworkspace.
Open Pickflavorviewcontroller.swift and add the following code under the existing import:
Click Command+b to compile. If everything is fine, you will not receive any compilation errors.
Next, replace the Loadflavors () method with the following code
12345678910111213141516 |
private func loadFlavors() {
let urlString =
"http://www.raywenderlich.com/downloads/Flavors.plist" // 1
Alamofire.request(.GET, urlString, encoding: .PropertyList(.XMLFormat_v1_0, 0))
.responsePropertyList { request, response, array, error
in
// 2
if
let error = error {
println(
"Error: \(error)"
)
// 3
}
else
if
let array = array as? [[String: String]] {
// 4
if
array.isEmpty {
println(
"No flavors were found!"
)
// 5
}
else
{
self.flavors = self.flavorFactory.flavorsFromDictionaryArray(array)
self.collectionView.reloadData()
self.selectFirstFlavor()
}
}
}}
|
The following is a detailed description of the process:
1. You created a GET request with Alamofire and downloaded a plist file containing ice cream flavors.
2. Generally you go to see if the request is faulted and resolves the error. Now if something goes wrong, you just need to print the error.
3. Convert an array of anyobject. Type to a dictionary array.
4. If the array is empty, you only need to print an error message.
5. If everything is OK, you will assign the array containing the flavor object created by the Flavorfactory method to Self.flavors. This is a class that a colleague writes for you and is used to convert an array of dictionary-type objects into a flavor object. You can take a closer look at this factory class if you like, but it's not particularly important for other parts of the tutorial.
Compile and run! Now you can choose an ice cream flavor!
Selection of Decorative objects
The app looks great, but you can still optimize it.
Did you notice that the app took a few seconds to download the flavors file? If your network is fast, you may not notice, but users will not be so fortunate.
To let users understand what the app is loading now, you can display a load indicator. Mbprogresshud is a great loading indicator. And it supports cocoapods, what a coincidence!
You need to add this to your podfile. You don't have to open podfile from the command line now, you can find it in the pods of the workspace.
Open Podfile and add the following lines after Alamofire:
1 |
pod ‘MBProgressHUD‘ , ‘~> 0.9.0‘ |
Save the file and install the dependent file in the terminal via the pod Install command, just as you did before.
Did you find anything different this time? Yes, you wrote the specific version number ~>0.9.0. What's going to happen here?
Cocoapods recommends that all pods use the semantic version number (Semantic Versioning).
Semantic version number
These three numbers are defined as primary, secondary, and patch version numbers. For example, the version number 0.9.0 will be translated to
When the number of major (major) version numbers increases, it means that you do some updates that are not compatible with older versions. When you upgrade the pod to the next major version, you may need to fix compilation errors, or the pod might not behave the same as before.
When the minor (minor) version number increases, it means that new functionality is added, but it is compatible with older versions. When you decide to upgrade, you may or may not need new features, but it should not cause compilation errors or change existing functionality.
When the patch version number increases, this means that a bug fix has been made. But there is no increase or change in functionality. In general, you will want to update the patch version to the latest version as soon as possible to use the latest and most stable version of the pod.
Finally, the highest version number (Major>minor>patch) must be incrementally increased according to the above rules, and the lower version number must start at 0.
Need an example?
Consider a pod with the current version of 1.2.3.
If you do some changes that are not backwards compatible, no new functionality, but you have modified the existing bug, the next version is 2.0.0
Challenge Time
1. If the current version number of a pod is 2.4.6, and has made some bug fixes, and added some backward compatibility features, what should be the new version??
Answer: 2.5.0
Explanation: If you modify a new feature that contains backward compatibility, the minor version number (Monir) is incremented, and the patch version number (patch) is set to 0.
2. If the current version of a pod is 3.5.8, and has made some changes to the current functionality, what should the new version be?
Answer: 4.0.0
Explanation: If the change modifies the existing functionality, then this is not backwards compatible. Therefore, the major version number (major) must be increased, while the minor and supplemental versions are set to 0.
3. What should the new version number be if the forward version number of a pod is 10.20.30 and fixes only a few bugs?
Answer: 10.20.31
Explanation: If the bug is fixed only, the Supplemental version number (patch) will increase.
With so much to say, here's an exception:
If the version of a pod is less than 1.0.0, which is considered a beta version, the addition of minor version number (minor) may imply a change in backwards compatibility.
So using ~>0.9.0 in Mbprogresshub means you need to install the latest version that is greater than or equal to 0.9.0 but less than 0.10.0.
This ensures that you get the latest bug fixes when installing pods, but not accidentally pulling backwards-compatible changes. There are a few other available operations here. For a specific list, see Podfile Syntax Reference.
Show process
Now, go back to Pickflavorviewcontroller.swift and add the following to the other references below
Next, add the following methods after Loadflavors ()
12345 |
private func showLoadingHUD() { let hud = MBProgressHUD.showHUDAddedTo(contentView, animated: true ) hud.labelText = "Loading..." } private func hideLoadingHUD() { MBProgressHUD.hideAllHUDsForView(contentView, animated: true )} |
Now in the Loadflavors () method, add the following code:
123456 |
private func loadFlavors() {
let urlString =
"http://www.raywenderlich.com/downloads/Flavors.plist"
showLoadingHUD()
// <-- Add this line
Alamofire.request(.GET, urlString, encoding: .PropertyList(.XMLFormat_v1_0, 0))
.responsePropertyList { request, response, array, error
in
self.hideLoadingHUD()
// <-- And this line if let error = error {
//...
|
As the method name indicates, the Showloadinghud () method produces an Mbprogresshud instance object when the GET request is downloaded, and Hideloadinghud () hides the HUD when the request ends. Because Showloadinghud () is outside the closure, it does not require the predecessor code self.
Compile and run. Now you'll see a load indicator:
What a beautiful job! Users can now choose their favorite ice cream flavors, and a loading indicator is displayed when the flavor file is downloaded.
Next
You can download the full project from here
Congratulations, now that you've learned the basics of using cocoapods, including creating and modifying dependency files, and understanding the semantic version numbers. Now you are ready to start using them in your own projects.
Of course you can do a lot of other things with cocoapods. You can search for existing pods on the official website of Cocoapods. You can also refer to the Cocoapods Guide to learn more details on how to use this outstanding tool. But remember, once you start using it you'll wonder how you used to manage it!
How to use Cocoapods-b in Swift