Swift - EVReflection (二)

使用EVReflection 和 Alamofire 通过构造Request实体类,实现发送HTTP请求。

  • JW_Request

首先构建 Request 基类,里面有域名,请求超时时间,发起请求等主要的属性和方法。

import Foundation
import UIKit
import Alamofire
import EVReflection

class JW_Request {
    
    var host = "https://xxx.com"

    var timeout: TimeInterval = 60
    
    static let Notification_Error = "com.JW.EVReflectionDemo.HTTP_Error_Notification"
    
    let notifitioncation: String
    
    let api: String
    
    var path: String? = "API"
    
    var bodyParameters: [String: Any]?
    
    var qureyParameters: [String: Any]?
    
    required init(notification: String, api: String, path: String = "API", bodyParameters: [String: Any]? = nil, qureyParameters: [String: Any]? = nil) {
        self.notifitioncation = notification
        self.api = api
        self.path = path
        self.bodyParameters = bodyParameters
        self.qureyParameters = qureyParameters
    }
    
    public func excute(sender: UIViewController?) {
        
        let successNotification = NSNotification.Name(rawValue: self.notifitioncation)
        let failNotification = NSNotification.Name(rawValue: JW_Request.Notification_Error)
        
        let request = makeRequest(api: self.api, qureyParameters: self.qureyParameters)

//        Session.default.request(request!).responseJSON { response in
//            switch response.result {
//            case .success(let value):
//                let responseData = self.getResponse(value as! NSDictionary)
//                print(responseData)
//                break
//            case .failure(let error):
//
//                print(error)
//            }
//        }

        Alamofire.Session.default.request(request).response { response in
            if response.response?.statusCode == 200 {
                
                let dictionary = try? JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.mutableContainers)
                
                NotificationCenter.default.post(name: successNotification, object: dictionary)
            } else {
                NotificationCenter.default.post(name: failNotification, object: response.error)
            }
        }
    }
    
    func getResponse(_ dictionary: NSDictionary) -> JW_Response {
        return JW_Response(dictionary: dictionary)
    }

}

extension JW_Request {
    
    private func makeRequest(api: String, qureyParameters: [String: Any]? = nil) -> URLRequest {
        let URL = URLBuilder(api: api)
        var urlRequest = URLRequest(url: URL)
        urlRequest.httpMethod = Alamofire.HTTPMethod.post.rawValue
        if qureyParameters == nil {
            urlRequest.httpMethod = Alamofire.HTTPMethod.get.rawValue
        }
        urlRequest.timeoutInterval = self.timeout
        return try! JSONEncoding.default.encode(urlRequest, with: qureyParameters)
    }
    
    func URLBuilder(api: String, queryParams: [String: Any]? = nil) -> URL {
                
        var baseQueryParams: [String: Any] = [:]
        baseQueryParams["APIToken"] = "xxx"
        baseQueryParams["APICommand"] = "xxx"

        if let realParams = queryParams {
            baseQueryParams.merge(realParams, uniquingKeysWith: {$1})
        }
        
        let baseURL = URL(string: self.host)
        var urlComponents = URLComponents.init()
        urlComponents.scheme = baseURL?.scheme
        urlComponents.host = baseURL?.host
        urlComponents.path = self.path!
        urlComponents.queryItems = baseQueryParams.map { URLQueryItem(name: $0, value: "\($1)") }
        
        return urlComponents.url!
    }
}

class JW_Response: EVObject {
    var result: String?
    var message: JW_ResponseResultMessage?
}

class JW_ResponseResultMessage: EVObject {
    var text: String?
    var title: String?
}
  • JWLoginRequest

以登录API为例,构造 登录请求的 request

import Foundation
import EVReflection

class JWLoginRequest: JW_Request {
    
    static let Notification = "com.JW.EVReflectionDemo.HTTP_Login_Notification"
    
    static let LoginAPI = "xxx"
    
    override func getResponse(_ dictionary: NSDictionary) -> JW_Response {
        return JWLoginResponse(dictionary: dictionary)
    }
    
    required init(userName: String, password: String) {
        super.init(notification: JWLoginRequest.Notification, api: JWLoginRequest.LoginAPI)
    }
    
    required init(notification: String, api: String, path: String = "API", bodyParameters: [String : Any]? = nil, qureyParameters: [String : Any]? = nil) {
        fatalError("init(notification:api:path:bodyParameters:qureyParameters:) has not been implemented")
    }
}

class JWLoginResponse: JW_Response {
    
    var data: JWLoginResponseData?
    
}

class JWLoginResponseData: EVObject {
    
   
}

通过构造请求的实体类,对请求进行抽象,将请求和返回抽象成实体类,通过继承实现一些功能。

唉😔,搞的好复杂,有没有点过渡封装的赶脚。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Morris_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值