【Swift CopoaPods的使用】

开发需要添加第三方库,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";
}

如果输出是对的就说明成功了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值