Developing a usable system, no matter how small, relies on third-party libraries, such as Alamofire, which is often used to access the network. CocoaPods is an excellent way to include dependencies into your project. For many open source repositories, CocoaPods builds a list of PodSpec files that specify where to download the code and how to integrate it with the current project.

In my own case, I started working on Swift in May and developed a CNode client for learning purposes. Initially, I decided to use some third-party open source libraries so I could focus on cNode’s own business logic:

Alamofire
ObjectMapper 
AlamofireObjectMapper
Cartography
Kingfisher 
GTMRefresh
DrawerController
SwiftIcons
PKHUD
Copy the code

With CocoaPods, just write a Podfile and write these files and versions:

use_frameworks! Target 'cnode' do pod 'Alamofire', '~> 4.4.0'... endCopy the code

You can use the POD command to update all dependencies in one click. Without it, I would have to copy the source files from these third-party open source libraries into the project or set them to git subModule. All those annoying dependencies and compile-parameter configurations can be eliminated with Pod.

This article explores how to use existing and tried-and-true Swift third-party pods, and how to create one of your own and publish it to the CocoaPods repository.

Using the Pod

Prepare CocoaPods

CocoaPods requires that Ruby is already installed in your system, if not, install it first.

You can use the following command:

sudo gem install cocoapods
Copy the code

Install the gem tool. Use immediately:

pod setup --verbose
Copy the code

After that, as long as the POD directory is not updated, use this command whenever possible (much faster) :

pod install --verbose --no-repo-update
Copy the code

Do the configuration. After executing the command, Cocoapods is available.

Create a demo project

The steps are as follows:

  1. Open the xcode
  2. Click “Create a new Xcode Project”
  3. Select the Single View App
  4. Fill in Product name as poddemo; Enter the language Swift
  5. Set the directory

After creation, exit Xcode

Initialize the

Open Terminal, navigate to the project directory, and run the following command:

pod init
Copy the code

This command creates the Podfile file in the directory. Next open the Podfile using Xcode:

open -a Podfile
Copy the code

Add a dependency to the Alamofire file and modify the Podfile to:

target 'poddemo' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for poddemo
  pod 'Alamofire', '~> 4.4'
end
Copy the code

Exit xcode and run the following command in terminal:

pod install
Copy the code

Install Alamofire and create a file with the extension xcWorkspace.

Use Alamofire to access HTTP

Open the xcWorkspace file again using Xcoce. Edit Appdelegate. swift to:

import UIKit import Alamofire @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window : UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { foo() window = UIWindow() window! .rootViewController = UIViewController() window! .rootViewController! .view.backgroundColor = .blue window! .makeKeyAndVisible() return true } func foo(){ Alamofire.request("https://httpbin.org/get").responseJSON { response in print(response.request) print(response.response) print(response.data) print(response.result) if let JSON = response.result.value { print("JSON: \(JSON)") } } } }Copy the code

Compile and run with the expected output:

Optional(https://httpbin.org/get) Optional(<NSHTTPURLResponse: 0x600000222840> { URL: https://httpbin.org/get } { status code: 200, headers { "Access-Control-Allow-Credentials" = true; "Access-Control-Allow-Origin" = "*"; Connection = "keep-alive"; "Content-Length" = 359; "Content-Type" = "application/json"; Date = "Wed, 26 Apr 2017 01:15:59 GMT"; Server = "gunicorn / 19.7.1"; 1.1 vegur Via = ""; } }) Optional(359 bytes) SUCCESS JSON: { args = { }; headers = { Accept = "*/*"; "Accept-Encoding" = "gzip; Q = 1.0, compress; Q = 0.5 "; "Accept-Language" = "en; Q = 1.0 "; Connection = close; Host = "httpbin.org"; "The user-agent" = "poddemo / 1.0 (home. Poddemo; build:1; IOS 10.2.0) Alamofire / 4.4.0 "; }; Origin = "221.237.156.243"; url = "https://httpbin.org/get"; }Copy the code

If the output is correct, the third-party library imported through CocoaPods has succeeded.

Create a Pod

You create a library function and want to share it. How to do? Cocoapods can help.

Ready to code

First, let’s create this Cocoa Touch framework. Add a swift file (name: robot.swift) with the following contents:

import Foundation
public func inc(_ i : Int)->Int{return i + 1}
Copy the code

Compile and pass.

Create a PodSpec file for this code

If you want CocoaPods to help you share, you need to write a spec file that describes the author, home page, license, and so on. It is particularly important to indicate the location of the source code.

Now navigate to the project directory and execute the following command:

touch robot.podspec
Copy the code

The pasted content is:

Pod: : Spec. New do | s | s.n ame = ‘robot’ s.v ersion = ‘0.1.0 from’ s.s ummary = ‘some bullshit s.d. escription =’ some bullshit Sheldon horowitz omepage = ‘https://github.com/1000copy/robot’ s.license = { :type => ‘MIT’, :file => ‘LICENSE’ } s.author = { ‘1000copy’ => ‘[email protected]’ } s.source = { :path => ‘~/github/pod/robot’ } S.iso. Deployment_target = ‘10.0’ s.deployce_files = ‘robot/*’ end

Of particular importance are S.name. s.sion, s.ource,s.source_files, without which publishing pod is impossible.

It is best to check that the podspec is correct by executing this command:

pod lib lint
Copy the code

Refer to pod

Create a Single View App project using POD and put it in UsePod

cd usepod pod init

Paste content into Podfile

pod ‘robot’,:path=> ‘~/github/pod/robot/robot.podspec’

Execute command:

pod install –verbose –no-repo-update

Reference code

Open the usepod.workspace file and paste the reference code into appdelegate. swift:

import UIKit
import robot
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window : UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        print(inc(41))
        return true
    }
}
Copy the code

Publish to the Github repository

Files will be posted to the Github repository, so a Github account is necessary. The repository needs to create a release because podSpec references this release. My related information:

  1. The Github account is 1000Copy
  2. The name of the repository used to store shared code: Robot

You need to substitute your corresponding information in the following commands and operations. First of all:

  1. Create a repository and name it Robot

  2. Navigate to your project directory from the command line and execute commands to deliver the code to the Github repository

    git init git add . git commit -m “init” git remote add origin git push -u origin master

  3. On Github, make a release of the repository with the version number set to 0.1.0, which will be referenced in your PodSpec file.

Published to cocoapods

Run the publish command, register your mail first, and then push podSpec.

pod trunk register [email protected]
pod trunk push robot.podspec
Copy the code

Note that cocoapods will send you an email that takes effect when you click on the confirm link.

You should see feedback like this:

 🎉  Congrats

 🚀  robot (0.1.0) successfully published
 📅  August 16th, 06:03
 🌎  https://cocoapods.org/pods/robot
 👍  Tell your friends!
Copy the code

Now you can use Robot just like any other POD.

Some principle

When configuring a POD using the pod Setup command, you’ll find that the command takes a long time to execute, which makes me wonder what it’s actually downloading.

I explored the local storage and found something about cocoapod’s internal organizational level.

In fact, CocoaPods pulls down the entire Pod warehouse, which is housed in ~/.Cocoapods. My size here is:

$du -sh ~/. Cocoapods 1.5g /Users/ LCJ /. CocoapodsCopy the code

Each open source library has multiple versions, and each version has a directory. Directories are stored here:

/Users/lcj/.cocoapods/repos/master/Specs/d/a/2/Alamofire
Copy the code

How many versions of this are available:

$ls/Users/LCJ /. Cocoapods/repos/master/Specs/d/a / 2 / Alamofire 1.1.3 2.0.0 3.0.0 - beta. 2 3.2.0 4.0.0 1.1.4 2.0.0 - beta. 1 3.0.0 - beta. 3 3.2.1 4.0.1 1.1.5 2.0.0 - beta. 2 3.0.1 3.3.0 4.1.0 1.2.0 2.0.0 - beta. 3 3.1.0 3.3.1 4.2.0 1.2.1 2.0.0 - beta. 4 3.1.1 3.4.0 4.3.0 1.2.2 2.0.1 3.1.2 3.4.1 track 4.4.0 1.2.3 2.0.2 3.1.3 3.4.2 4.5.0 1.3.0 3.0.0 3.1.4 3.5.0 4.5.1 1.3.1 3.0.0 - beta. 1 3.1.5 3.5.1 track ofCopy the code

The podSpec file for Alamofire version 1.1.3 is this:

$ls/Users/LCJ /. Cocoapods/repos/master/Specs/d/a / 2 / Alamofire / 1.1.3 / Alamofire podspec. Json

As follows:

$cat/Users/LCJ /. Cocoapods/repos/master/Specs/d/a / 2 / Alamofire / 1.1.3 / Alamofire podspec. Json {" name ": "Alamofire", "version": "1.1.3", "License ": "MIT"," Summary ": "Elegant HTTP Networking in Swift", "homepage": "https://github.com/Alamofire/Alamofire", "social_media_url": "http://twitter.com/mattt", "authors": { "Mattt Thompson": "[email protected]" }, "source": { "git": "https://github.com/Alamofire/Alamofire.git", "tag": 1.1.3 ""}," platforms ": {" ios" : "8.0"}, "source_files" : "Source / *. Swift," "requires_arc" : true}Copy the code

With the above analysis, you can see how CocoaPods executes install each time. Find the podSpec file, compare it to the source specified by the soure attribute in the file, and update the latest repository to the local directory if any changes are found.

I have reservations as to whether it is appropriate to save the entire warehouse to the client.

Reference:

  1. http://blog.devtang.com/2014/05/25/use-cocoapod-to-manage-ios-lib-dependency/
  2. http://ishalou.com/blog/2012/10/16/how-to-create-a-cocoapods-spec-file/
  3. http://www.yudiz.com/creating-your-own-ios-framework-and-distributed-using-cocoapods/
  4. https://stackoverflow.com/questions/16020216/working-with-git-submodules-cocoapods