iOS 知识库

对AlamofireObjectMapper进行二次封装

2017-10-14  本文已影响20人  z小志

1、pod导入AlamofireObjectMapper

platform :ios, ‘8.0’

target 'project' do

use_frameworks!

pod 'Alamofire'
pod 'AlamofireObjectMapper'

end

pod install

2、根据后台返回数据(公共部分)配置baseModel

import UIKit
import ObjectMapper

class MDBaseModel: Mappable {
    var code : Int?
    var msg : String?
    required init?(map: Map) { }
    
    func mapping(map: Map) {
        code <- map["code"]
        msg <- map["msg"]
    }
}

3、封装

import UIKit
import Alamofire
import ObjectMapper
import AlamofireObjectMapper

class MDNetRequest: NSObject {
    static let share = MDNetRequest()
    
    
    private override init() {}
    
    var manger:SessionManager?
    
    func post<T: MDBaseModel>(url: String, params:[String: Any]?, successBlock: @escaping (_ result: T) -> Void,failBlock:@escaping (_ code:Int,_ msg:String) -> Void, errorBlock: @escaping (_ error: NSError) -> Void) {
        Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: ["platform":"ios","version-code":AppInfo.buildVersion,"session-id":MDDataSource.share.session==nil ? "" : MDDataSource.share.session!])
            .responseObject { (response: DataResponse<T>) in
            if let err = response.result.error {
                errorBlock(err as NSError)
            }else {
                if response.result.value?.code == 0 {
                    successBlock(response.result.value!)
                }else{
                    failBlock((response.result.value?.code)!,(response.result.value?.msg)!)
                }
            }
        }
    }
    
}

3、使用:以登录为例

MDHubHelper.share.showStatus(msg: "登录中")
MDNetRequest.share.post(url: UrlLogin, params: ["account":t_accout.text!,"password":t_password.text!,"phoneid":MDSaver.share.getUUID()], successBlock: { (result:MDLoginModel) in
    MDHubHelper.share.hidHubView()
    MDSaver.share.setAccount(account: self.t_accout.text!)
    MDSaver.share.setPassword(password: self.t_password.text!)
    MDDataSource.share.session = result.data?.token
    UIApplication.shared.keyWindow?.rootViewController = getHomeSBVC("MDHomeViewController")as!MDHomeViewController
    
}, failBlock: { (code, msg) in
    MDHubHelper.share.showError(msg: msg)
}) { (err) in
    showRequestErr(code: err.code)
}

备注:MDLoginModel
import UIKit
import ObjectMapper

class MDLoginModel: MDBaseModel {
    var data : MDLoginDataModel?
    
    required init?(map: Map) {
        super.init(map: map)
    }
    
    override func mapping(map: Map) {
        super.mapping(map: map)
        data <- map["data"]
    }
    
}

class MDLoginDataModel: Mappable {
    var token : String?
    required init?(map: Map) { }

    func mapping(map: Map) {
        token <- map["token"]
    }
}

MDLoginModel 继承 MDBaseModel
上一篇下一篇

猜你喜欢

热点阅读