美文网首页Alamofire全面解析
Alamofire框架介绍篇一

Alamofire框架介绍篇一

作者: 谌文 | 来源:发表于2019-06-03 20:39 被阅读0次

一: Alamofire的由来

iOS开发的小哥哥们,如果使用过OC开发的APP的肯定都使用过,或者起码会知道APP与后台网络请求三方库AFNetworking,可以它简直就是iOS开发的,那Alamofire是什么呢,它就是大神作者Matt Thompson开发的一个新的类似Alamofire的使用swift语言开发的网络基础库。

二: Alamofire的使用

1-1、注意下CocoaPods版本


gem install cocoapods

CocoaPods 0.39.0+ is required to build Alamofire 3.0.0+.

1-2、vim Podfile


platform :ios,'8.0'

use_frameworks! 

pod'Alamofire'//然后 pod install 就OK了

1-3、导入Alamfire 就可以正常使用了


import Alamofire

注意目前可能会出现这个警告;Cannot load underlying module for 'Alamofire',可以先忽略它,直接 build就没了

二、基本使用

GET请求

普通的get请求

class ViewController: UIViewController {
    // MARK :网络请求管理类
    var sessionManager:Alamofire.SessionManager!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 15
        sessionManager = Alamofire.SessionManager(configuration: configuration)
        /// 下面是一个天气预报的请求,时间久了,key 会失效
        let parameters:Dictionary = ["key":"93c921ea8b0348af8e8e7a6a273c41bd"]
        sessionManager.request("http://apis.haoservice.com/weather/city", method: .get, parameters: parameters).responseJSON { (response) in
            print("result==\(response.result)")   // 返回结果,是否成功
            if let jsonValue = response.result.value {
                print("code: \(jsonValue)")
            }
        }
    }
}

带header的get请求

class ViewController: UIViewController {
    // MARK :网络请求管理类
    var sessionManager:Alamofire.SessionManager!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 15
        sessionManager = Alamofire.SessionManager(configuration: configuration)
        let headers = ["apikey":"a566eb03378211f7dc9ff15ca78c2d93"]
        let parameters:Dictionary = ["city":"beijing"]
        sessionManager.request("http://apis.haoservice.com/weather/city", method: .get, parameters: parameters).responseJSON { (response) in
            print("result==\(response.result)")   // 返回结果,是否成功
            if let jsonValue = response.result.value {
                print("code: \(jsonValue)")
            }
        }
    }

至于加header的post 请求,实际上也是GET 一样的

POST 请求

先看看Alamofire 定义了许多其他的HTTP 方法(HTTP Medthods)可以使用。

public enum HTTPMethod: String {
    case options = "OPTIONS"    
    case get     = "GET"
    case head    = "HEAD"
    case post    = "POST"
    case put     = "PUT"
    case patch   = "PATCH"
    case delete  = "DELETE"
    case trace   = "TRACE"
    case connect = "CONNECT"
}

使用GET类型请求的时候,参数会自动拼接在url后面,使用POST类型请求的时候,参数是放在在HTTP body里传递,url上看不到的

 class ViewController: UIViewController {
    // MARK :网络请求管理类
    var sessionManager:Alamofire.SessionManager!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 15
        sessionManager = Alamofire.SessionManager(configuration: configuration)
        /// 下面是一个天气预报的请求,时间久了,key 会失效
        let parameters:Dictionary = ["key":"93c921ea8b0348af8e8e7a6a273c41bd"]
        sessionManager.request("http://apis.haoservice.com/weather/city", method: .post, parameters: parameters).responseJSON { (response) in
            print("result==\(response.result)")   // 返回结果,是否成功
            if let jsonValue = response.result.value {
                
                print("code: \(jsonValue)")
            }
        }
    }   

至于加header的post 请求,实际上也是GET 一样的

注意点1: 参数编码方式

除了默认的方式外,Alamofire还支持URLEncoding、JSONEncoding、PropertyListEncoding。 其他编码或者自定义编码需要自己实现ParameterEncoding协议来自定义

public protocol ParameterEncoding {
    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
}
/// 
public struct URLEncoding: ParameterEncoding {
}
///
public struct JSONEncoding: ParameterEncoding {
}
///
public struct PropertyListEncoding: ParameterEncoding {
}

//想要把一个字典类型的数据,使用json格式发起POST请求

  let parameters:Dictionary = [
            "one": [1,2,3],
            "two": ["apple": "pig"]
            ] as [String : Any]
  sessionManager.request("http://apis.haoservice.com/weather/city", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
             }
        }

注意点2:validate()

validate() 1可以通过定位是否是请求失败或者后台特殊code来确定是否需要重连请求,2,并且可以通过实现 RequestRetrier来实现是否需要重连,实现RequestAdapter来重连时是否需要修改请求参数

/// validate() 使用
    func requestByValidate() {
        let parameters:Dictionary = [
            "one": [1,2,3],
            "two": ["apple": "pig"]
            ] as [String : Any]
        sessionManager.retrier = OAuth2Handler()
        sessionManager.adapter = OAuth2Handler()
        sessionManager.request("http://app-server.inside.xiaoeknow.com/api/check_phone", method: .post, parameters: parameters, encoding: JSONEncoding.default).validate()
            { request, response, data in
                guard let data = data else {
                    return .failure("dr" as! Error)  // 打回重连
                }
                /// 将服务器返回的Data转Dictionary
                let dictionary = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)as! Dictionary<String,Any>
                let retCode = dictionary?["code"] as? Int
                /// retCode = -1 是参数错误
                if retCode == -1 {
                    let error = EncodingError.invalidValue("", EncodingError.Context.init(codingPath: [], debugDescription: "-1"))
                    return .failure(error)   //打回重连
                }
                return .success    //校验通过,不重连
            }.responseJSON { (response) in
            print("result==\(response.result)")   // 返回结果,是否成功
            if let jsonValue = response.result.value {
                print("code: \(jsonValue)")
            }
        }
    }
}

/// 重连机制
class OAuth2Handler: RequestRetrier, RequestAdapter {
    /// 修改请求参数
    /// Request的参数需要到OAuth2Handler的RequestAdapter回调中修改
    func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
        var urlRequest = urlRequest
        var body = try! JSONSerialization.jsonObject(with: urlRequest.httpBody!, options:.mutableContainers) as! [String : Any]
         body["change"] = "\(arc4random() % 10)"
        urlRequest.httpBody = try! JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
        return urlRequest
    }
    
    public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: RequestRetryCompletion) {
        if let _ = error as? EncodingError {
            completion(true, 1.0) // 不重连
        } else {
            completion(false, 0.0) // 不重连
        }
    }
}

暂时基本使用,总结到此,持续更新中····⛽️ 缺少重连次数使用,暂时未找到使用方法

备注参考

https://github.com/Alamofire/Alamofire
http://www.hangge.com/blog/cache/detail_970.html
http://www.cnblogs.com/iCocos/p/4550570.html

相关文章

网友评论

    本文标题:Alamofire框架介绍篇一

    本文链接:https://www.haomeiwen.com/subject/esphxctx.html