Swift iOS:CocoaPods的使用
开发需要添加第三方库,Swift的访问网络库Alamofire来举例。
添加CocoaPods,有了CocoaPods,需要编写Podfile,写入Alamofire的名称和版本号:
use_frameworks!
target 'cnode' do
pod 'Alamofire', '~> 4.4.0'
...
end
使用pod命令( pod install ),一键生成所有的依赖库。
使用Alamofire进行网络请求
编辑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";
}
如果输出是对的就说明成功了。