cocopod-AlamoFire<转>

Alamofire框架的介绍和使用

转自<http://www.jianshu.com/p/dc7e7d5b0ae6>

一. 什么是Alamofire

(1)Alamofire 的前身是 AFNetworking。AFNetworking 是 iOS 和 OS X 上很受欢迎的第三方HTTP网络基础库。
(2)其实 AFNetwork 的前缀 AF 便是 Alamofire 的缩写。
(3)Swift发布后,AFNetworking的作者又用Swift语言写了个相同功能的库,这便是 Alamofire。
(4)Alamofire 本质是基于URLSession,并做了封装。使用 Alamofire 可以让我们网络请求相关代码(如获取数据,提交数据,上传文件,下载文件等)更加简洁易用。

二. Alamofire的使用

1.Alamofire使用了步骤

我在使用这个框架的时候是用的cocoapods导入的方式,当然也可以手动导入,本人感觉使用cocoapods比较方便,下面就是介绍一下cocoapods导入该库的方法:(如果有的同学想要知道手动导入的步骤,可以参考这链接Alamofire手动导入方法)

(1).更新cocoapods的版本

cocoapods的使用方法我想对于大多数开发者来说肯定是再熟悉不过了,这里就略过了,如果有什么疑问的地方可以去看一下我之前写过的文章关于cocoapods的使用,或者查阅一些资料。这里我做了一些特殊的处理方法。如果我们直接使用之前版本安装的cocoapods来更新Alamofire最新版本可能会更新失败,这里我们需要把cocoapods的版本升级到1.1.0+的版本才可以。
首先提到的一点是,在xcode8之后的cocoapods的镜像已经有taobao的gem源换成了ruby.china的gem源。但是我在更换了路径之后还是失败了很多次,最后就索性换成了 使用国内的spec镜像就可以了!

 cd ~/.cocoapods/repos  
 git clone https://git.coding.net/CocoaPods/Specs.git master

如果显示master文件存在可以在~/.cocoapods/repos 路径下先把master文件删除,在进行替换,不过这个过程比较缓慢,请耐心等待即可。
更换完路径后,再使用:

sudo gem install cocoapods --pre

更新cocoapods的版本即可(可以参照这里的一篇文章点击这里)

(2).更新完cocoapods版本之后就是用cocoapods更新Alamofire的最新版本即可。
2.Alamofire的功能特点

(1).链式的请求/响应方法
(1).URL / JSON / plist参数编码
(2).上传类型支持:文件(File )、数据(Data )、流(Stream)以及MultipartFormData
(3).支持文件下载,下载支持断点续传
(4).支持使用NSURLCredential进行身份验证
(5).HTTP响应验证
(6).TLS Certificate and Public Key Pinning
(7).Progress Closure & NSProgress

3.Alamofire的网络请求

(1).get请求

 // get
    func GET_Request() {
        let parameters : [String : Any] = ["foo": "bar"]

        //1,responseJSON
        Alamofire.request(main_url, method: .get, parameters: parameters).responseJSON { (returnResult) in
             print("GET_Request --> GET 请求 --> returnResult = (returnResult)")

        if let json = returnResult.result.value {
            print("firstMethod --> responseJSON --> (json)")
            /*  返回请求地址、数据、和状态结果等信息
             print("firstMethod --> responseJSON() --> (returnResult.request!)")
             print("firstMethod --> responseJSON() --> (returnResult.data!)")
             print("firstMethod --> responseJSON() --> (returnResult.result)")
             */
        }
        }

(2).post请求

    // post
    func POST_Request(){


        //request(host_url, method:.post, parameters : parameters)

        let urlstring = "(host_url)type=(top)&key=(appkey)"

        Alamofire.request(urlstring, method:.post).responseJSON { (returnResult) in
             print("POST_Request --> post 请求 --> returnResult = (returnResult)")
//            switch returnResult.result.isSuccess {
//            case true:
//                print("数据获取成功!")
//            case false:
//                print(returnResult.result.error ?? Error.self)
//            }

        }
    }

(3).响应处理(Response Handling)
除了上面样例使用的responseJSON(处理json类型的返回结果)外,Alamofire还提供了许多其他类型的响应处理方法:

response()  
responseData()  
responseString(encoding: NSStringEncoding)  
responseJSON(options:NSJSONReadingOptions)  
responsePropertyList(options: NSPropertyListReadOptions)
       //2,response()
//        Alamofire.request(main_url, method:.get, parameters: parameters).response { (response) in
//            print("response = (response.response)")
//            print("data = (response.data)")
//            print("error = (response.error)")
//            
//            
//            if let data = response.data , let utf8string = String(data: data , encoding:.utf8) {
//                print("utf8string = (utf8string)")
//            }
//            
//        }




        //3,responseData()
//        Alamofire.request(main_url, method: .get, parameters: parameters).responseData { (responseData) in
//            debugPrint("responseData : (responseData)")
//            
//            if let data = responseData.data, let utf8string = String(data: data, encoding: .utf8) {
//                print("utf8string = (utf8string)")
//            }
//            
//        }



//        //4,responseString
//        Alamofire.request(main_url, method: .get, parameters: parameters).responseString { (responseString) in
//            debugPrint("responseString() --> Sucess = (responseString.result.isSuccess)")
//             debugPrint("responseString : (responseString)")
//            
//            if let data = responseString.data , let utf8string = String(data: data, encoding: .utf8) {
//               print("utf8string = (utf8string)")
//            }
//        }



        // 5. responsePropertyList()  下面解释



        //6.在response方法中还有一个方法  参数:queue:请求队列 --> 就是默认在主线程中执行~但是我们可以自定义调度队列。
//        let customQueue = DispatchQueue.global(qos: .utility)
//        Alamofire.request(main_url, method: .get, parameters: parameters).responseJSON(queue: customQueue) { (returnResult) in
//            print("请求队列 --> (returnResult)")
//        }

(4)下载,上传

//下载 上传

    func downloadAnduploadMethod() {
        //下载文件
        Alamofire.download(host_img_url).responseJSON { (returnResult) in
            if let data = returnResult.result.value {
                let image = UIImage(data : data as! Data)
                print("(image)")
            }else {
                print("download is fail")
            }
        }

        //还可以看下载进度
        Alamofire.download(host_img_url).downloadProgress { (progress) in
             print("download progress = (progress.fractionCompleted)")
        }.responseJSON { (returnResult) in
            if let data = returnResult.result.value {
                let image = UIImage(data : data as! Data)
                print("(image)")
            }else {
                print("download is fail")
            }
        }

    }
原文地址:https://www.cnblogs.com/deng37s/p/7428172.html