Swift4.x 使用Alamofire请求(对Alamofire进行简单的封装),使用苹果原生 Codable 解析数据model,并实际应用到UITableView中

在开始工作前首先需要先引入第三方 网络请求

Alamofire ,如何引用我的上一篇文章有所设计,可以参考下

首先贴出一段数据

{
    "activityList": [

        {
            "name": "新年签抽抽抽 领奖",

            "startTime": "2018-02-14 09:39",

            "endTime": "2018-09-30 09:39",
            "address": "",

            "isStart": "1",
            "isEnd": "1",

            "signupNum": "0",

            "imageUrl": "",
            "displayType": "1",

            "url": "http://10.30.140.11:8000/clt/publish/clt/resource/portal/v1/activityDetail.jsp?c=5293914",
            "signupUrl": "http://10.30.140.11:8000/clt/clt/activitySignup.msp?c=5293914&activityId=5293914"
        },
        {
            "name": "11122",

            "startTime": "2017-08-09 09:03",

            "endTime": "2018-07-25 09:03",
            "address": "发放稿费",

            "isStart": "1",
            "isEnd": "1",

            "signupNum": "11",

            "imageUrl": "http://10.30.140.11:8000/clt/publish/clt//image/4/475/774.jpg",
            "displayType": "0",

            "url": "http://10.30.140.11:8000/clt/publish/clt/resource/portal/v1/activityDetail.jsp?c=4696044",
            "signupUrl": "http://10.30.140.11:8000/clt/clt/activitySignup.msp?c=4696044&activityId=4696044"
        }
    ]
}

其次我们贴出 controller中的代码,这里的代码使用了 OC的MJRefresh的代码,如果不需要可以自行去掉

import UIKit

class MActivityViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    fileprivate var currentTabelView:UITableView?
    fileprivate var dataModel:MyActivityListModel?
    fileprivate var dataArray:NSMutableArray?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        
        //headerView
        let headerView = HeaderNavigationView.init()
        headerView.titleString = "我的活动"
        headerView.isShowLineView = true
        if isIphoneXSeries() {
            headerView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 88)
        } else {
            headerView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 64)
        }
        self.view.addSubview(headerView)
        
        // footerView
        let footerView = GeneralBottomView.init()
        if isIphoneXSeries() {
            footerView.frame = CGRect(x: 0, y: self.view.frame.size.height - 60, width: SCREEN_WIDTH, height: 60)
        } else {
            footerView.frame = CGRect(x: 0, y: self.view.frame.size.height - 40, width: SCREEN_WIDTH, height: 40)
        }
       weak var weakSelf = self
        footerView.setBackMyClosure{ () -> Void in
            weakSelf?.navigationController?.popViewController(animated: true)
        }
        self.view.addSubview(footerView)
        
       
        self.currentTabelView = UITableView.init(frame: CGRect(x: 0, y: headerView.frame.maxY, width: SCREEN_WIDTH, height: self.view.frame.size.height - headerView.frame.height - footerView.frame.height))
        self.view.addSubview(self.currentTabelView!)
        self.currentTabelView!.backgroundColor = UIColor.white
        self.currentTabelView!.separatorStyle = UITableViewCellSeparatorStyle.none
        //设置数据源
        self.currentTabelView!.dataSource = self
        //设置代理
        self.currentTabelView!.delegate = self
        self.currentTabelView!.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "MyactivityTableViewCell")
        
        self.dataArray = NSMutableArray.init()

        self.currentTabelView?.mj_header = XWRefreshHeader.init(refreshingBlock: {
            //请求数据
            weakSelf?.loadNewData()
        })
        self.currentTabelView?.mj_header.beginRefreshing()
    }
    //MARK:请求新的数据
    func loadNewData(){        
        let urlString = String(format: "%@%@", CZTV_Foundation_URL, Cztv_ActivityList_url)
        //加密
        let serverString  = EncryptUrl.sharedInstance.encryptUrlWithOriginalUrl(originalUrl: urlString)
        let parameters:[String : Any] = [:]
        
        weak var weakSelf = self
        SwiftNetWorkManager.sharedInstance.postRequest(serverString, params: parameters, success: { (dictResponse) in
//            print("我参加活动的数据是\(jsonString)")
            weakSelf?.currentTabelView?.mj_header.endRefreshing()
            let loaclData = dictResponse as Data
            do {
                weakSelf?.dataModel = try JSONDecoder().decode(MyActivityListModel.self, from: loaclData)
//                debugPrint("student====\(self.dataModel!.activityList)")
                weakSelf?.currentTabelView?.reloadData()
            } catch {
//                debugPrint("student===ERROR")
            }
        }) { (error) in
            //               print("-----错误是\(error)")
            if error._code == NSURLErrorTimedOut {
                //超时
                FSHUDMananger.showMessage("请求超时,请稍后再试", completion: nil)
            } else {
                FSHUDMananger.showMessage("服务器出了点小问题,请稍后再试", completion: nil)
            }
        }
    }
    //MARK:加载tabelView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if self.dataModel == nil{
            return 0
        }
        if self.dataModel!.activityList.count != 0  {
            return self.dataModel!.activityList.count
        }
        return 0;
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let indentifier = "MyactivityTableViewCell"
        
        var cell:MyactivityTableViewCell! = tableView.dequeueReusableCell(withIdentifier: indentifier)as?MyactivityTableViewCell
        if cell == nil {
            cell = MyactivityTableViewCell(style: .default, reuseIdentifier: indentifier)
        }
        cell.selectionStyle = UITableViewCell.SelectionStyle.none
        cell.detailModel = self.dataModel!.activityList[indexPath.row] as DetailModel
        return cell
    }
    
    //MARK:加载tabelView的代理
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let detailModel = self.dataModel!.activityList[indexPath.row] as DetailModel
        let detailVC : XWActivityDetailViewController =  XWActivityDetailViewController.init(activityName: detailModel.name, url: detailModel.url)
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return MyactivityTableViewCell.myactivityTableViewCellHeight()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }  
    deinit {
        
    }
}

从以上的controller的代码中我们看到了 网络请求的封装。以下就是封装的网络请求的代码,代码使用了单例保证调用的一次性,回调使用的闭包的方式,简化controller中的代码调用

import UIKit
import Alamofire

public typealias Success = (_ data : Data)->()
public typealias Failure = (_ error : Error)->()

class SwiftNetWorkManager: NSObject {
    //单例
    static var sharedInstance : SwiftNetWorkManager {
        struct Static {
            static let instance : SwiftNetWorkManager = SwiftNetWorkManager()
        }
        return Static.instance
    }
    
    /// GET请求
     func getRequest(
        _ urlString: String,
        params: Parameters? = nil,
        success: @escaping Success,
        failure: @escaping Failure)
    {
        request(urlString, params: params, method: .get, success, failure)
    }
    
    /// POST请求
     func postRequest(
        _ urlString: String,
        params: Parameters? = nil,
        success: @escaping Success,
        failure: @escaping Failure)
    {
        
        request(urlString, params: params, method: .post, success, failure)
    }
    
    //公共的私有方法
    private func request(
        _ urlString: String,
        params: Parameters? = nil,
        method: HTTPMethod,
        _ success: @escaping Success,
        _ failure: @escaping Failure)
    {
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 10
        manager.request(urlString, method: method, parameters:params).responseData { response in
            guard let json = response.result.value else {
                return
            }
            switch (response.result) {
            case .success:
                success(response.data! as Data)
                break
            case .failure(let error):
                failure(error)
                break
            }
        }
    }
}

在controller中,我们还有model的数据,其中model的解析采用 苹果原生的 Codable方式,以下贴出model的代码,数据的第一层是数组

import Foundation


struct MyActivityListModel:Codable {
    var activityList:[DetailModel] = []
}

struct DetailModel:Codable {
    var address:String
    var displayType: String
    var endTime:String
    var imageUrl:String
    var isEnd:String
    var isStart:String
    var name:String
    var signupNum:String
    var signupUrl:String
    var startTime:String
    var url:String
   
}

其中还涉及到了 cell的部分,以下是cell中的代码,cell中包含初始化控件,set方法辅助,还有计算cell的高度 类方法

import UIKit

class MyactivityTableViewCell: UITableViewCell {
    
    fileprivate var titleLabel:UILabel?      // 活动标题
    fileprivate var timeView:ActivityLabelView?      // 开始-结束 时间
    fileprivate var addressView:ActivityLabelView?   // 活动地址
    fileprivate var signupNumView:ActivityLabelView? // 报名人数

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.backgroundColor = UIColor.white
        
        self.titleLabel = UILabel.init(frame: CGRect(x: 10, y: 10, width: SCREEN_WIDTH, height: 28))
        self.titleLabel?.font = UIFont.systemFont(ofSize: 22)
        self.titleLabel?.textColor = UIColor.black
        self.titleLabel?.textAlignment = NSTextAlignment.left
        self.contentView.addSubview(self.titleLabel!)
        
        self.timeView = ActivityLabelView.init(frame: CGRect(x: 10, y: self.titleLabel!.frame.maxY + 10, width: SCREEN_WIDTH - 20, height: 12))
        self.timeView?.leftImageNameStr =  "activity_time"
        self.contentView.addSubview(self.timeView!)
        
        self.addressView = ActivityLabelView.init(frame: CGRect(x: 10, y: self.timeView!.frame.maxY + 10, width: SCREEN_WIDTH - 20, height: 12))
        self.addressView?.leftImageNameStr =  "activity_add"
        self.contentView.addSubview(self.addressView!)
        
        self.signupNumView = ActivityLabelView.init(frame: CGRect(x: 10, y: self.addressView!.frame.maxY + 10, width: SCREEN_WIDTH - 20, height: 12))
        self.signupNumView?.leftImageNameStr =  "activity_num"
        self.contentView.addSubview(self.signupNumView!)
        
        let bottomLineView = UIView.init(frame: CGRect(x: 0, y: self.signupNumView!.frame.maxY + 10, width: SCREEN_WIDTH, height: 10))
        bottomLineView.backgroundColor = UIColor.init(white: 0.95, alpha: 1)
        self.contentView.addSubview(bottomLineView)
        
    }
    //set赋值方法
    var detailModel:DetailModel? {
        didSet{
            self.titleLabel?.text = detailModel!.name
            self.timeView?.rightString = "\(String(describing: detailModel!.startTime)) —— \(String(describing:detailModel!.endTime))"
            self.addressView?.rightString = detailModel!.address
            self.signupNumView?.rightString = "\(String(describing:detailModel!.signupNum))已报名"
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
    //MARK: cell的高度
    class func myactivityTableViewCellHeight() -> CGFloat{
        return 10 + 28 + 10 + 12 + 10 + 12 + 10 + 12 + 10 + 10;
    }
}

事实上这个已经是个完整的“简单”的swift版本的请求,解析,赋值,布局tableView的过程。
如果有什么不正确之处,望大神指出,谢谢。!
效果图
DDC8590B88C67223572E8801DCF4E305.png

你可能感兴趣的:(Swift4.x 使用Alamofire请求(对Alamofire进行简单的封装),使用苹果原生 Codable 解析数据model,并实际应用到UITableView中)