Swift iOS : CocoaPods

CocoaPods是一個iOS項目的依賴管理器,使用它能夠讓導入第三方庫和處理依賴關係變得簡單。javascript

出於測試和驗證的目的,這裏會建立一個Swift工程,並採用CocoaPods導入第三方HTTP庫alamofire。java

準備CocoaPods

CocoaPods須要系統內已經安裝了ruby,若是沒有安裝,請首先安裝它。能夠使用以下命令:json

sudo gem install cocoapods複製代碼

安裝此工具。隨即便用:swift

pod setup --verbode複製代碼

作配置。命令執行完畢,cocoapods就是可用的了。xcode

建立一個演示工程

步驟以下:ruby

  1. 打開xcode
  2. 點擊「Create a new Xcode project」
  3. 選擇Single View App
  4. 填寫product name爲poddemo;填寫語言爲Swift
  5. 設置目錄

完成建立後,退出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的文件。

使用Alamofire訪問HTTP

再次使用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導入的第三方庫已經成功。

相關文章
相關標籤/搜索