美文网首页
简单记录Alamofire的使用

简单记录Alamofire的使用

作者: 辛乐 | 来源:发表于2019-10-24 14:06 被阅读0次
    1.Alamofire超时时间的设置
    2.get和post选择的ParameterEncoding
    3. headers的设置
    4.调试打印response的数据
    
    //
    //  SwiftHttpTool.swift
    //  DCEX
    //
    //  Created by APBC on 2019/10/22.
    //  Copyright © 2019 BITHUMB GLOBAL PROJECT. All rights reserved.
    //
    
    import UIKit
    import Alamofire
    import SwiftyJSON
    
    enum MethodType: Int {
        case GET
        case POST
        
        public var httpMethod: HTTPMethod {
            switch self {
            case .GET:
                return HTTPMethod.get
            case .POST:
                return HTTPMethod.post
            }
        }
        
        public var encoding: ParameterEncoding {
            switch self {
            case .GET:
                return URLEncoding.default
            case .POST:
                return JSONEncoding.default
            }
        }
    }
    
    enum MimeType: String {
        case PNG = "image/png"
        case MOV = "video/mp4"
        
        public var fileType: String {
            switch self {
            case .PNG:
                return ".png"
            case .MOV:
                return ".mp4"
            }
        }
    }
    
    @objcMembers
    class SwiftHttpTool: NSObject {
    
        public static let `default` = SwiftHttpTool()
        private override init() {}
        
        //MARK: 设置超时时间
        static let sharedSessionManager: Alamofire.SessionManager = {
            let configuration = URLSessionConfiguration.default
            configuration.timeoutIntervalForRequest = 15.0
            return Alamofire.SessionManager(configuration: configuration)
        }()
        
        //MARK: 统一处理header
        func getHttpHeaders(params:[String:Any]) -> HTTPHeaders {
           
            let header = [
                         "ClientType":"iOS,\(Global.APP.uuid)",
                         "Language":PreferenceService.currentLanguage().customValueForHeader,
                         "CounterId":"2",
                         "client":"ios",
                         "apiKey":UserService.default.getLoginSecurityInfo()?.respId ?? "",
                         "apiTimestamp":HttpParamEncodeTool.getTimestamp(),
                         "apiSignature":HttpParamEncodeTool.getapiSignature(withParams: params),
                         "Content-Type":"application/json"
            ]
            return header
        }
        
        //MARK: 网络请求
        func request(method: MethodType,urlStr: String,params :[String : Any],success :@escaping ((JSON)->()), fail : @escaping ((String)->())){
            
            let header : HTTPHeaders = self.getHttpHeaders(params: params)
            print("请求的header:\(header)")
            
            SwiftHttpTool.sharedSessionManager.request(urlStr, method: method.httpMethod, parameters: params,encoding: method.encoding, headers: header)
            // 添加手工验证返回Http状态码
            .validate(statusCode: 200..<300)
            // 添加手工验证返回contentType类型
            .validate(contentType: ["application/json"])
            .responseJSON {[weak self] (response) in
                
                self?.testResponse(response: response)
                
                switch response.result {
                case .success(let value):
                    print("请求的结果是:\(value)")
                    let json = JSON(value)
                    if "\(json["code"])" == "0" {
                        success(json["info"])
                    }else{
                        let msg = "\(json["msg"])"
                        fail(msg)
                    }
                case .failure(let error):
                    print("请求错误是:")
                    print(error)
                    fail("网络接口层错误")//此处可以返回 网络未连接 或者 网络信号异常等报错
                }
            }
        }
        
        //MARK: 上传文件
        func uploadFile(data:Data,file:String,fileName:String,mimeType: MimeType,toUrl:String, params :[String : String],success :@escaping ((JSON)->()), fail : @escaping ((String)->())) {
            
            print("请求的url:\(toUrl)")
            var header : HTTPHeaders = self.getHttpHeaders(params: params)
            header["Content-Type"] = "multipart/form-data"
            print("请求的header:\(header)")
            
            SwiftHttpTool.sharedSessionManager.upload(multipartFormData: { (formData) in
                
                for (key,value) in params {
                    
                    guard let data = value.data(using: .utf8) else { return }
                    formData.append(data, withName: key)
                    print("请求的data:\(data) key:\(key)")
                }
                
                formData.append(data, withName: file, fileName: (fileName + mimeType.fileType), mimeType: mimeType.rawValue)
                print("请求的formData:\(formData), fileName: \(fileName + mimeType.fileType),mimeType: \(mimeType.rawValue)")
            }, to: toUrl, headers: header) { (result) in
                switch result {
                case .success(let upload, _, _):
                    upload.responseJSON { (response) in
                        switch response.result{
                        case .success(let value):
                            print("上传文件成功:\(value)")
                            let json = JSON(value)
                            if "\(json["code"])" == "0" {
                                success(json["info"])
                            }else{
                                let msg = "\(json["msg"])"
                                fail(msg)
                            }
                            break
                        case .failure(let error):
                            print("上传文件error2:\(error)")
                            fail("网络接口层错误")//此处可以返回 网络未连接 或者 网络信号异常等报错
                            break
                        }
                    }
                    break
                case .failure(let error):
                    print("上传文件error1:\(error)")
                    fail("网络接口层错误")//此处可以返回 网络未连接 或者 网络信号异常等报错
                    break
                }
            }
        }
        
        //MARK: 调试打印返回信息
        func testResponse(response : DataResponse<Any>)  {
            
            print("请求的结果response.request:")
            print(response.request ?? "失败")    // original URL request
            print("请求的结果response.request.httpBody")
            print(String.init(data: response.request?.httpBody ?? Data.init(), encoding: .utf8) ?? "body失败")
            print("请求的结果response.request.allHTTPHeaderFields")
            print(response.request?.allHTTPHeaderFields ?? "headers无数据")
            print("请求的结果response.data:")
            let str = String.init(data: response.data!, encoding: .utf8)
            print(str ?? "")
            print("请求的结果response.result:")
            print(response.result)          // result of response serialization
        }
        
    }
    

    以下是个人使用习惯


    image.png image.png image.png

    相关文章

      网友评论

          本文标题:简单记录Alamofire的使用

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