本文介绍: Swift iOS:CocoaPods使用开发需要添加第三方库,Swift访问网络库Alamofire来举例。使用Alamofire进行网络请求开发需要添加第三方库,Swift访问网络库Alamofire来举例。添加CocoaPods,有了CocoaPods需要编写Podfile,写入Alamofire名称版本号use_frameworks!targetcnodedo pod ‘Alamofire‘, ‘~> 4.4.0′ …end使用pod命令

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

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

原文地址:https://blog.csdn.net/AHekey/article/details/122838420

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_16469.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注