Swift封装一个网络数据请求的类

作者: 9ad91f89b29e | 来源:发表于2016-08-04 21:23 被阅读829次

    在用MVC设计模式的时候,如果网络数据多的话,controller会占用很多空间。为了解决这个问题,可以封装一下数据请求,下面是我封装的类,供大家参考下。
    先把代码贴出来:

    说明:
    * 通过HomeDynamicDataType这个枚举来选择是那种类型的数据
    * 通过pageNoforRequestDynamicData这个protocol方法来确定每次请求加载第几页
    * 通过pageSizeforRequestDynamicData这个protocol方法来确定每页加载多少个
    * 通过requestParmsforHomeDynamicDataSource来根据不同的HomeDynamicDataType来生成不同的parms
    * 通过responseforHomeDynamicDataRequest这个protocol方法来监听数据加载情况
    * ZHYNetworkingManager为AFNetworking的一个请求的简单封装
    * 在判断delegate是否响应protocol方法时,这样if let pageSize = self.delegate?.pageSizeforRequestDynamicData?()
      不要用if self.delegate?.pageSizeforRequestDynamicData?() != nil
      不然的话在在后边赋值parms["pageNo"] = self.delegate?.pageSizeforRequestDynamicData?()
      会执行两次pageSizeforRequestDynamicData方法
    
    //HomeDataManager.swift
    @objc enum HomeDataRequestStatus:Int {//网络请求状态
        case Normal
        case NoNetWork
        case TimeOut
    }
    
    @objc protocol HomeDataManagerDelegate:NSObjectProtocol {
        func responseforHomeDynamicDataRequest(response:NSArray?,status:HomeDataRequestStatus)
        optional func pageNoforRequestDynamicData() -> Int
        optional func pageSizeforRequestDynamicData() -> Int
    }
    
    class HomeDataManager: NSObject {
        enum HomeDynamicDataType {//数据类型
            case HomeAuthoritativeInformation//首页数据
            case AuthoritativeInformation//权威发布
            case PartyConstitution//党章
            case PartyrulesAndDisciplines//党规党纪
            case PartyHistory//党史
            case SecretarySpeech//系列讲话
        }
        
        var delegate:HomeDataManagerDelegate?
        
        class func sharedInstance() -> HomeDataManager {
            struct Static {
                static let instance = HomeDataManager()
            }
            return Static.instance
        }
        
        private override init() { }    
        
        func dataRequestforHomeDynamic(type:HomeDynamicDataType) {
            let parms = self.requestParmsforHomeDynamicDataSource(type)
            
            if let pageNo = self.delegate?.pageNoforRequestDynamicData?() {
                parms["pageNo"] = pageNo
            }
            
            if let pageSize = self.delegate?.pageSizeforRequestDynamicData?()  {
                parms["pageSize"] = pageSize
            }
            
            ZHYNetworkingManager.sharedInstance().post("http://*********", parameters: parms, progress: nil,
                               success: {
                                (task, response) -> Void in
                                let rows = response!["rows"] as? NSArray
                                self.delegate?.responseforHomeDynamicDataRequest(rows, status: .Normal)
    
                })
            { (task, error) -> Void in
                print("请求失败")
                self.delegate?.responseforHomeDynamicDataRequest(nil, status: .TimeOut)
            }
    
        }
    
    }
    
    extension HomeDataManager {
        func requestParmsforHomeDynamicDataSource(type:HomeDynamicDataType) -> NSMutableDictionary {
            let dict =  ["token": "FD65C7F1-10AA-4A3F-BF41-F3F285883FCD",
                         "keyword":"" ,
                         "pageSize": 7,
                         "pageNo": 1,
                         "type": 4,
                         "childType": 1
            ]
            let parms = NSMutableDictionary(dictionary: dict)
            
            switch type {
            case .HomeAuthoritativeInformation:
                parms["pageSize"] = 4
                parms["type"] = 1
                return parms
            case .AuthoritativeInformation:
                parms["type"] = 1
                return parms
            case .PartyConstitution:
                return parms
            case .PartyHistory:
                parms["childType"] = 2
                return parms
            case .PartyrulesAndDisciplines:
                parms["childType"] = 3
                return parms
            case .SecretarySpeech:
                parms["childType"] = 4
                return parms
            }
            
        }
    }
    
    //ZHYNetworkingManager.swift
    import AFNetworking
    
    class ZHYNetworkingManager:NSObject {
        
        class func sharedInstance() -> ZHYNetworkingManager {
            struct Static {
                static let instance = ZHYNetworkingManager()
            }
            return Static.instance
        }
        
        private override init() {}
        
        func post(url :String , parameters : AnyObject? , progress:((NSProgress) -> Void)?,success :((NSURLSessionDataTask, AnyObject?) -> Void)? ,failure :((NSURLSessionDataTask?, NSError) -> Void)?) {
            
            //AFNetWorking发送POST请求
            let manager:AFHTTPSessionManager = AFHTTPSessionManager()
            
            manager.requestSerializer = AFJSONRequestSerializer()
            manager.requestSerializer.timeoutInterval = 5.0
            //接受的MIME格式
            manager.responseSerializer = AFJSONResponseSerializer()
            
            //异步加载
            manager.POST(url, parameters: parameters, progress: progress, success:success, failure: failure)
        }
        
        func get(url :String! , parameters: AnyObject?, progress: ((NSProgress) -> Void)?, success: ((NSURLSessionDataTask, AnyObject?) -> Void)?, failure: ((NSURLSessionDataTask?, NSError) -> Void)?) {
            //AFNetWorking发送POST请求
            let manager:AFHTTPSessionManager = AFHTTPSessionManager()
            
            manager.requestSerializer = AFJSONRequestSerializer()
            manager.requestSerializer.timeoutInterval = 5.0
            //接受的MIME格式
            manager.responseSerializer = AFJSONResponseSerializer()
            
            //异步加载
            manager.GET(url, parameters: parameters, progress: progress, success: success, failure: failure)
        }
        
    }
    

    应用

    private var pageNo:Int = 0    
    lazy var dataManager:HomeDataManager? = {
        let ahomeDataManager = HomeDataManager.sharedInstance()
        ahomeDataManager.delegate = self
        return ahomeDataManager
    }()
    //下拉加载
    func headerRefreshAction() {
         pageNo = 0        
         self.dataManager?.dataRequestforHomeDynamic(.AuthoritativeInformation)
    }
    //上拉加载更多
    func footRefreshAction() {
        self.dataManager?.dataRequestforHomeDynamic(.AuthoritativeInformation)
    }
    //Mark: - HomeDataManagerDelegate
    func responseforHomeDynamicDataRequest(response: NSArray?, status: HomeDataRequestStatus) {
        if status == .Normal {
           print("请求成功")
        }else {           
           print("请求失败")       
        }
    }    
    func pageNoforRequestDynamicData() -> Int {
        pageNo += 1
        return pageNo
     }
    
    

    相关文章

      网友评论

        本文标题:Swift封装一个网络数据请求的类

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