CocoaPods是一个iOS项目的依赖管理器,使用它能够让导入第三方库和处理依赖关系变得简单。javascript
出于测试和验证的目的,这里会建立一个Swift工程,并采用CocoaPods导入第三方HTTP库alamofire。java
CocoaPods须要系统内已经安装了ruby,若是没有安装,请首先安装它。能够使用以下命令:json
sudo gem install cocoapods复制代码
安装此工具。随即便用:swift
pod setup --verbode复制代码
作配置。命令执行完毕,cocoapods就是可用的了。xcode
步骤以下:ruby
完成建立后,退出xcodeapp
打开Terminal,导航到工程目录,执行命令:工具
pod init复制代码
此命令会在目录内建立Podfile文件。接下来使用xcode打开Podfile文件:测试
open -a Podfile复制代码
加入alamofire文件的依赖,修改后的Podfile为:ui
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复制代码
退出xcode,在terminal内执行命令:
pod install复制代码
安装Alamofire,而且建立一个扩展名为xcworkspace的文件。
再次使用xcoce打开xcworkspace文件。编辑AppDelegate.swift为:
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)")
}
}
}
}复制代码
编译运行,指望的输出为:
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"; Via = "1.1 vegur"; } }) 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"; "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"; }复制代码
若是输出是对的,就说明经过CocoaPods导入的第三方库已经成功。