Swift4.x 使用Alamofire請求(對Alamofire進行簡單的封裝),使用蘋果原生 Codable 解析數(shù)據(jù)model,并實際應(yīng)用到UITableView中

在開始工作前首先需要先引入第三方 網(wǎng)絡(luò)請求

Alamofire ,如何引用我的上一篇文章有所設(shè)計,可以參考下

首先貼出一段數(shù)據(jù)

{
    "activityList": [

        {
            "name": "新年簽抽抽抽 領(lǐng)獎",

            "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": "發(fā)放稿費",

            "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
        //設(shè)置數(shù)據(jù)源
        self.currentTabelView!.dataSource = self
        //設(shè)置代理
        self.currentTabelView!.delegate = self
        self.currentTabelView!.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "MyactivityTableViewCell")
        
        self.dataArray = NSMutableArray.init()

        self.currentTabelView?.mj_header = XWRefreshHeader.init(refreshingBlock: {
            //請求數(shù)據(jù)
            weakSelf?.loadNewData()
        })
        self.currentTabelView?.mj_header.beginRefreshing()
    }
    //MARK:請求新的數(shù)據(jù)
    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("我參加活動的數(shù)據(jù)是\(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("服務(wù)器出了點小問題,請稍后再試", 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的代碼中我們看到了 網(wǎng)絡(luò)請求的封裝。以下就是封裝的網(wǎng)絡(luò)請求的代碼,代碼使用了單例保證調(diào)用的一次性,回調(diào)使用的閉包的方式,簡化controller中的代碼調(diào)用

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的數(shù)據(jù),其中model的解析采用 蘋果原生的 Codable方式,以下貼出model的代碼,數(shù)據(jù)的第一層是數(shù)組

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?      // 開始-結(jié)束 時間
    fileprivate var addressView:ActivityLabelView?   // 活動地址
    fileprivate var signupNumView:ActivityLabelView? // 報名人數(shù)

    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;
    }
}

事實上這個已經(jīng)是個完整的“簡單”的swift版本的請求,解析,賦值,布局tableView的過程。
如果有什么不正確之處,望大神指出,謝謝。!
效果圖
DDC8590B88C67223572E8801DCF4E305.png

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容