非入门篇:服务器后端+MJRefresh第三方库的上拉刷新与下拉刷新

此篇非入门篇,入门请简友移步 http://www.hangge.com/blog/cache/search.php?key=Mjrefresh

看似简单的下拉,上拉,其实还蛮复杂的,值得好好研究!

写在贴代码之前,首先得思考几个问题:
1、下拉时得查找服务器上最新的数据 然后填充Model
2、再次下拉时,查找服务器上是否再有新的数据了,有的话再把新的加在数组在前面
3、不要每次下拉都清空Model,再把下拉的数据都填充到Model,试想想,如果用户本来已经上拉了500条数据在手机里,你再一下拉,岂不是把用户本机上的都清空了?(一定要和后台配合好,通过MaxID值或者其它值来判断)
4、上拉时,相对简单点,有新的数据,就直接把新的数据加在数组的后面就行了,没有的话,就提示用户没有再多数据就可以了。

话唠嗑多了,直接上代码了,MVVC+服务器后端JSON 共5个文件!
一、MODEL

//
//  NewsModel.swift
//  Created by apiapia on 5/30/17.
//  Copyright © 2017 apiapia. All rights reserved.

import UIKit
import HandyJSON

// 有用的数据才建立MODEL

class NewsDataModel:HandyJSON {
    
    var totalPage:Int?
    var total:Int?
    var list:[NewsListModel]?
    required init(){}
}

class NewsListModel:HandyJSON {
    
    var releaseDate:String?
    var newsId:Int16?
    var programaName:String?
    var image:String?
    var title:String?
    
    required init(){}
}


二、VIEW

import UIKit
import Kingfisher
import SwifterSwift

class NewsTableViewCell: UITableViewCell {

    var releaseDate:UILabel!
    var newsId:String?
    var programaName:UILabel!
    var newsImage:UIImageView!
    var title:UILabel!
    // 存放标题文字的内空
    var titleContent:UIView!
    var imagesAPI = IMAGESAPI
    
    var newsList:NewsListModel? {
    
        didSet {
            // 把表格的CELL显示在这
            self.title.text = newsList?.title
          
            let resource   = ImageResource.init(downloadURL: URL.init(string:"\(imagesAPI)\((newsList?.image!)!)")!)
            let cache      = KingfisherManager.shared.cache
            let optionsInfo = [KingfisherOptionsInfoItem.transition(ImageTransition.fade(1)),
                              KingfisherOptionsInfoItem.targetCache(cache),
                              KingfisherOptionsInfoItem.processor(RoundCornerImageProcessor(cornerRadius: 50))]
            
            newsImage.kf.setImage(with: resource,
                                  placeholder: UIImage(named:"placeholder"),
                                  options: optionsInfo,
                                  progressBlock: nil,
                                  completionHandler: nil)
           // FIXME: verison 1.0.1 时 待优化 -- 已优化 on 2017-06-04
           // newsImage.layer.cornerRadius = 10  // 代码不要用
           // newsImage.layer.masksToBounds = true
            self.programaName.text = newsList?.programaName
            self.releaseDate.text = newsList?.releaseDate
        }
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        // initialize code
        self.selectionStyle = UITableViewCellSelectionStyle.none
        // 约束先确认图片的显示,读取缓存,速度更快
        self.newsImage = UIImageView()
        self.addSubview(self.newsImage)
        
        self.title = UILabel()
        self.title.font = UIFont.systemFont(ofSize: 14)
        self.addSubview(self.title)
        
         self.titleContent = UIView.init()
         self.addSubview(self.titleContent)
        
        // MARK: - 图片
        self.newsImage.snp.makeConstraints { (make) -> Void in
            make.height.equalTo(80)
            make.right.equalToSuperview().offset(-14)
            make.top.equalToSuperview().offset(8)
            make.bottom.equalToSuperview().offset(-8)
            make.width.equalTo(self.newsImage.snp.height)
        }

        // MARK: - 标题 view
        // 文字内容背景
        titleContent.backgroundColor = UIColor.clear
        self.addSubview(titleContent)
        titleContent.snp.makeConstraints { (make) in
            // 表格宽度
            make.top.equalTo(self.newsImage.snp.top).offset(2)
            make.right.equalTo(self.newsImage.snp.left).offset(-10)
            make.left.equalToSuperview().offset(8)
            make.bottom.equalTo(self.newsImage.snp.bottom).offset(-10)
        }
        // 标题
        // MU认只显示一行
        title.numberOfLines = 0
        title.snp.makeConstraints { (make) in
            
            make.edges.equalTo(titleContent).inset(UIEdgeInsets.init(top: 2, left: 5, bottom: 5, right: 5))
        }
        // FIXME: - CA
        self.programaName = UILabel.init()
        self.programaName.font = UIFont.systemFont(ofSize: 12)
        self.programaName.textColor = UIColor(red: 201/255, green: 1/255, blue: 1/255, alpha: 1)
        self.programaName.backgroundColor = UIColor(red: 201/255, green: 1/255, blue: 1/255, alpha: 0.1)
      
        self.programaName.layer.borderColor = UIColor.red.cgColor
        self.programaName.layer.borderWidth = 0.5
        self.programaName.layer.masksToBounds = true
        self.programaName.textAlignment = .center
        
       self.addSubview(self.programaName)
        programaName.snp.makeConstraints { (make) in
            make.left.equalTo(title.snp.left)
            make.bottom.equalTo(newsImage.snp.bottom).offset(-2)
            make.width.equalTo(55)
        }

        // MARK: - 时间
        self.releaseDate = UILabel.init()
        self.releaseDate.textColor = UIColor.lightGray
        self.releaseDate.font = UIFont.systemFont(ofSize: 12)
        self.addSubview(self.releaseDate)
        
        releaseDate.snp.makeConstraints { (make) in
         //   make.centerX.equalTo(programaName)
            make.bottom.equalTo(newsImage.snp.bottom).offset(-2)
            make.right.equalTo(newsImage.snp.left).offset(-50)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }

}

三、VIEWMODEL

import UIKit
import SwiftyJSON
import HandyJSON
import MJRefresh
import SVProgressHUD

class NewsListViewModel {
    lazy var newsDataModel = NewsDataModel()
    lazy var newsList = [NewsListModel]()

    // 加载数据
    func loadData(maxID:Int64 = 0,sinceID:Int64 = 0,isPullUp:Bool,completion:@escaping (_ isSuccess:Bool)->()) {
        //isPullUp 表示是上拉刷新
        let urlString = NewsListAPI
        let params = [
                   "pageNo":1 as AnyObject,
                   "pageSize":10 as AnyObject,
                   "iOSVersion":"\(iOSVERSION)" as AnyObject,
                   "maxID":"\(maxID)" as AnyObject,
                   "sinceID":"\(sinceID)" as AnyObject
        ]
        print (params)
        // 最新数据
        BasePageApi.requestAPI(urlString,params){ [weak self] (result, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "加载失败,请检查网络")
                completion(false)
                return
            }
            // SwiftyJSON
            guard let dict = result?["result"] as? NSDictionary else {
               // SVProgressHUD.dismiss()
                completion(false)
                return
            }
           self?.newsDataModel =  JSONDeserializer<NewsDataModel>.deserializeFrom(json: JSON(dict).description, designatedPath: "data")!
            
            // 上拉刷新
            if isPullUp {
                
                if self?.newsDataModel.list?.count != 0 {
                    
                    self?.newsList += (self?.newsDataModel.list!)!
                    completion(true)
                }else{
                    
                    print ("没有更多的数据了")
                    completion(false)    
                }
  
            } else {
                
                // 下拉刷新 如果有最新数据newsDataModel.list,则把数据放在数组在前面
                
                if self?.newsDataModel.list?.count != 0 { 
                    self?.newsList = (self?.newsDataModel.list!)! + (self?.newsList)!
                    completion(true)
                }else {
                    print ("已经是最新数据了")
                    completion(true)
                }
            }
            print ("是否\(isPullUp)上拉刷新,共刷新到:\((self?.newsDataModel.list?.count) )条数据")
       }
    }
}

四、CONTROLLERS

import UIKit
import SwiftyJSON
import HandyJSON
import MJRefresh
import SVProgressHUD
import DZNEmptyDataSet

class NewsTableViewController: UITableViewController,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate {
    
    fileprivate var statusBarShouldLight = true

    lazy var newsListViewModel = NewsListViewModel()
    var maxID:Int64 = 0
    var sinceID:Int64 = 0
    var isPullUp = false // 是否上拉刷新
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // self.navBarBgAlpha
        
        navigationController?.hidesBarsOnSwipe = true
        // 设为true ,表格就不会在navigation下方
        automaticallyAdjustsScrollViewInsets = true
        self.tableView.tableFooterView?.frame = CGRect.zero
        self.tableView.emptyDataSetSource = self
        self.tableView.emptyDataSetDelegate = self
        
        // 手工建立 tableViewCell的话,就要注册 cell 了
        tableView.register(NewsTableViewCell.self, forCellReuseIdentifier: "NewsItemCell")
        tableView.estimatedRowHeight = 150.0
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.tableFooterView = UIView()
        // 设置分割线从最左开始
        if tableView.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
            tableView.separatorInset = UIEdgeInsets.zero
        }
        // 加载数据
        initData(maxID:maxID,sinceID:sinceID,isPullUp: false)
        // 刷新数据
        initRefresh()
        // 视图自动调整
        self.view.layoutIfNeeded()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    // 重写navigation的title
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationItem.title = "资讯"
        /*关闭自动刷新功能 06.24 */
        // self.tableView.mj_header.beginRefreshing()
        
    }
    // MARK: - 刷新数据
    func initRefresh(){
        // MARK: - 下拉刷新
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            // SVProgressHUD.show(withStatus: "加载数据中")
            // 表示下拉刷新
            self?.isPullUp = false
            // 取得数组中的最大的ID,传给服务器,如果也是最大的ID,则服务器就返回 空数组 on 2017-06-02
            self?.maxID = self?.newsListViewModel.newsList.first?.newsId != nil ? Int64((self?.newsListViewModel.newsList.first?.newsId)!) : 0
            // print (self?.maxID ?? "")

            // 下拉刷新 时候把 sinceID 设为 0
            DispatchQueue.main.async {
                self?.initData(maxID: (self?.maxID)!, sinceID: 0, isPullUp: false)
            }
        })
        // 设置自动切换透明度(在导航栏下面自动隐藏)
        tableView.mj_header.isAutomaticallyChangeAlpha = true         
        //MARK: - 上拉刷新
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { [weak self] in
            
           // SVProgressHUD.show(withStatus: "加载更多数据")
            // 表示上拉刷新
            self?.isPullUp = true
            // 上拉的时候,服务器找出 select top 5  from table where sinceID < 477
            // 判断 newsList的newsID,是否为nil再进行 ! ,on 06.05.2017
            self?.sinceID = self?.newsListViewModel.newsList.last?.newsId != nil ? Int64((self?.newsListViewModel.newsList.last?.newsId)!) : 0
            // print (self?.sinceID ?? "")
            // 上拉刷新的时候把 maxID设为0 
            DispatchQueue.main.async {
               self?.initData(maxID: 0, sinceID: (self?.sinceID)!, isPullUp: true)
            } 
  }) 
          tableView.mj_footer.isAutomaticallyHidden =  true
    }
    
    // 加载数据
    func initData(maxID:Int64,sinceID:Int64,isPullUp:Bool) {
        print ("**********" ,isPullUp , "**********")
        // 把 数据加载 都放在ViewModel去处理  
        DispatchQueue.main.async {
          self.newsListViewModel.loadData(maxID:maxID,sinceID:sinceID,isPullUp:isPullUp) {[weak self] (isSuccess) in
           // SVProgressHUD.dismiss()
            self?.tableView.mj_header.endRefreshing()
            self?.tableView.mj_footer.endRefreshing()
            if isSuccess {
                // print (isSuccess)
                self?.tableView.reloadData()
                // self?.tableView.mj_footer.resetNoMoreData()
            }else
            {
            // 这个要判断是否没有更多的数据了
            //  self?.tableView.mj_footer.endRefreshingWithNoMoreData()
            // self?.tableView.mj_footer.isAutomaticallyHidden =  true
            // print ("是否上拉" , (self?.isPullUp)!)
            // MARK: -  下拉刷新时虽然 没有更多的值,但不要把设置 endRefreshingWithNoMoreData,因为设了后就不能上拉了 ON 2017-06-02
            self?.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
          }
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

extension NewsTableViewController  {
    
    // MARK: - tableView DataSource
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    // MARK: - tableView Delegate
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return  newsListViewModel.newsList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NewsItemCell", for: indexPath) as! NewsTableViewCell
        cell.newsList = self.newsListViewModel.newsList[indexPath.row]
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let detailsVC = DetailsViewController()        
        let id:Int16 = newsListViewModel.newsList[indexPath.row].newsId!
        // MARK:- 正向传值  easygoing 
        detailsVC.id = id
        
        navigationController?.setNavigationBarHidden(false, animated: true)
        // FIXME: pushViewController 被拦截 AppDelegate+TabBar+Nav
        navigationController?.pushViewController(detailsVC, animated: true)
    }
    
    
    // MARK: - scrollView 显示、hidden
    override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        
       // print("\(velocity.y)")
        if(velocity.y>0)
            
        {
            self.navigationController?.setNavigationBarHidden(true, animated: true)
        }
        else
        {
            self.navigationController?.setNavigationBarHidden(false, animated: true)
    
        }
    }
    
    // MARK: - 单元格动态变化 
   override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    
//    cell.layer.transform = CATransform3DMakeRotation(1, 1, 1, 1)
//        UIView.animate(withDuration: 0.25, animations: {
//            cell.layer.transform = CATransform3DMakeTranslation(1, 1, 1)
//        })
    }

}
// MARK: - 占位图及重新加载事件
extension NewsTableViewController {
    
    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage {
        return UIImage(named: "logo")!
    }
// FIXME:返回可以点击的按钮 上面带文字
//    func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControlState) -> NSAttributedString {
//        let attribute: [String: Any] = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: CGFloat(15.0))]
//        return NSAttributedString(string: "[重新加载]", attributes: attribute)
//    }
    
    //FIXME: #pragma mark - DZNEmptyDataSetDelegate
    // 处理按钮的点击事件
//    func emptyDataSet(_ scrollView: UIScrollView, didTap button: UIButton) {
//        print ("重新加载")
//        
//    }
    func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
        return -100
    }
    
}
class BasePageApi: NSObject {
    
    /* URL 可变  1、2、3 三个可合并,因为 urlString 已为可变 */
    class func requestAPI(_ urlString:String,_ params:[String:AnyObject], _ finished:@escaping (_ result: AnyObject?, _ error: NSError?) -> ()) {
        XMNetworkTool.shareInstance.xm_requestData(methodType: .GET, urlString: urlString, parameters: params) { (result, error) in
            finished(result, error)
        }
    }
}
import UIKit
import Alamofire

enum XMRequestType: Int {
    case GET
    case POST
}

class XMNetworkTool: NSObject {
    static let shareInstance : XMNetworkTool = {
        let tools = XMNetworkTool()
        return tools
    }()
}


extension XMNetworkTool {
    func xm_requestData(methodType:XMRequestType,urlString : String, parameters:[String : AnyObject]?,finished:@escaping(_ result: AnyObject?,_ error:NSError?) ->()){
        
        let resultCallBack = {(response: DataResponse<Any>) in
            if response.result.isSuccess {
                finished(response.result.value as AnyObject?,nil)
            }else{
                finished(nil, response.result.error as NSError?)
            }
        }
        // 2.请求数据
        let httpMethod: HTTPMethod = methodType == .GET ? .get : .post
        request(urlString, method: httpMethod, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON(completionHandler: resultCallBack)
    }
}

五、JSON (服务器后端)

<%@ WebHandler Language="C#" Class="index" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Text;


/*
 *  2017-06-30
 *  API接口 
 *  第一页
 *  http://api.elinknet.cn/news/findNewsList.do?iOSVersion=1.1.2&pageNo=1&pageSize=10
 *  上拉 第二页
 *  http://api.elinknet.cn/news/findNewsList.do?iOSVersion=1.1.2&pageNo=2&pageSize=10
 *  上拉第三页
 *  http://api.elinknet.cn/news/findNewsList.do?iOSVersion=1.1.2&pageNo=3&pageSize=10
    图片显示 http://images.elinknet.cn/2c1126e8-fc11-419c-8c62-05f54a221a73
 * 
 * 本地测试 http://localhost:53803/API/News/index.ashx?iOSVersion=1.0.0&pageNo=1&pageSize=10
 * 
 */


public class index : IHttpHandler {

    public void ProcessRequest(HttpContext context) {

        //  string pageNo = "1";      // 第几页
        // string pageSize = "10";   // 每一页共显示多少条数据
        string iOSVersion = "1.0.0"; // iOS 版本号
        string api = "";
        string maxID = "0";
        string sinceID = "0";


        // pageNo = context.Request.QueryString["pageNo"];
        // pageSize = context.Request.QueryString["pageSize"];
        iOSVersion = context.Request.QueryString["iOSVersion"];
        // 取得服务器中最大的ID,如果服务器有select from table from ID > maxID ,如果没有值,则返回空
        maxID = context.Request.QueryString["maxID"] != null ? context.Request.QueryString["maxID"] : maxID;
        // select from table from ID < sinceID ,如果有值,则返回更多数据

        sinceID = context.Request.QueryString["sinceID"] != null ? context.Request.QueryString["sinceID"] : sinceID;

        // SQL MAX ID 数据库当中最大的ID,即为最新数据 

        // simulate real data 

        // 第一次加载数据 



        if (Convert.ToInt64(maxID) == 0 && Convert.ToInt64(sinceID) ==0)

        {
            // 初始API 第一页 10 条数据
            api = "" +
           "{" +
           "\"errorCode\":0," +
           "\"message\":\"操作成功\"," +
           "\"result\":{\"businessCode\":0," +
           "\"message\":\"操作成功\"," +
           "\"data\":{" +
           "\"list\":[" +
           "{" +
           "\"newsId\":481," +
           "\"releaseDate\":\"2017-05-31\"," +
           "\"programaName\":\"标题标题\"," +
           "\"image\":\"2c1126e8-fc11-419c-8c62-05f54a221a73\"," +
           "\"title\":\"标题标题标题标题标题标题\"" +
           "}" +
           "," +
           "{" +
           "\"newsId\":480," +
           "\"releaseDate\":\"2017-05-30\"," +
           "\"programaName\":\"标题标题\"," +
           "\"image\":\"d9bb44aa-ea12-4bc4-a93d-5efc90e922e8\"," +
           "\"title\":\"标题标题标题标题标题标题标题标题标题标题\"" +
           "}" +

            "," +
           "{" +
           "\"newsId\":479," +
           "\"releaseDate\":\"2017-05-27\"," +
           "\"programaName\":\"标题标题\"," +
           "\"image\":\"58a524ed-11de-4b25-bdac-a34c4e602f17\"," +
           "\"title\":\"标题标题标题标题标题标题标题\"" +
           "}" +

            "," +
           "{" +
           "\"newsId\":478," +
           "\"releaseDate\":\"2017-05-26\"," +
           "\"programaName\":\"方案\"," +
           "\"image\":\"14fd5b43-c405-4955-b3c8-601286653e0e\"," +
           "\"title\":\"标题标题标题标题标题标题标题(06.26)上午推荐\"" +
           "}" +
            "," +
           "{" +
           "\"newsId\":477," +
           "\"releaseDate\":\"2017-05-25\"," +
           "\"programaName\":\"预测\"," +
           "\"image\":\"19e8e9a0-d467-403f-b48d-e186a913d8b6\"," +
           "\"title\":\"标题标题标题标题标题标题标题标题标题标题(06.27)上午推荐\"" +
           "}" +


           "]," +
           "\"totalPage\":0," +
           "\"total\":0" +
           "}" +
           "}" +
           "}" +
           "";

        }

        else
        {

            // 不是首次加载
            // 如果是select from table where ID(数据库的ID) > maxID 最大值,如果有则有数据,如果没有则返回无数据,则表示下拉刷新
            if (Convert.ToInt64(maxID) == 481 )
            {
                // 表示是下拉刷新,但是从 iOS客户端获得的 maxID = 481 为数据库当中最大的了 ...

                api = "" +
                "{" +
                "\"errorCode\":0," +
                "\"message\":\"操作成功\"," +
                "\"result\":{\"businessCode\":0," +
                "\"message\":\"操作成功\"," +
                "\"data\":{" +
                "\"list\":[" +





                "]," +
                "\"totalPage\":0," +
                "\"total\":0" +
                "}" +
                "}" +
                "}" +
                "";
            }

            else
            {

            // 这边要从数据库读出 top 5 出来 ,也要判断 maxID,不能上拉后立马上拉,maxID是还有值的
            if ( (Convert.ToInt64(sinceID) <= 477 && Convert.ToInt64(sinceID) > 472) )
            {
                //第二页

                api = "" +
                 "{" +
                 "\"errorCode\":0," +
                 "\"message\":\"操作成功\"," +
                 "\"result\":{\"businessCode\":0," +
                 "\"message\":\"操作成功\"," +
                 "\"data\":{" +
                 "\"list\":[" +


                 "{" +
                 "\"newsId\":476," +
                 "\"releaseDate\":\"2017-05-24\"," +
                 "\"programaName\":\"标题标题\"," +
                 "\"image\":\"a2780dd1-f2ac-439d-b229-c417186bebc3\"," +
                 "\"title\":\"标题标题标题标题标题标题标题标题(06.25)上午推荐\"" +
                 "}" +

                 "," +
                 "{" +
                 "\"newsId\":475," +
                 "\"releaseDate\":\"2017-05-24\"," +
                 "\"programaName\":\"标题标题标题\"," +
                 "\"image\":\"14fd5b43-c405-4955-b3c8-601286653e0e\"," +
                 "\"title\":\"标题标题标题标题标题标题标题标题(06.26)上午推荐\"" +
                 "}" +

                 "," +
                 "{" +
                 "\"newsId\":474," +
                 "\"releaseDate\":\"2017-05-23\"," +
                 "\"programaName\":\"3D预测\"," +
                 "\"image\":\"a2780dd1-f2ac-439d-b229-c417186bebc3\"," +
                 "\"title\":\"标题标题标题标题标题标题标题标题(06.25)上午推荐\"" +
                 "}" +

                 "," +
                 "{" +
                 "\"newsId\":473," +
                 "\"releaseDate\":\"2017-05-23\"," +
                 "\"programaName\":\"方案预测\"," +
                 "\"image\":\"14fd5b43-c405-4955-b3c8-601286653e0e\"," +
                 "\"title\":\"标题标题标题标题标题标题标题标题标题(06.25)上午推荐\"" +
                 "}" +

                 "," +
                 "{" +
                 "\"newsId\":472," +
                 "\"releaseDate\":\"2017-05-23\"," +
                 "\"programaName\":\"福利彩\"," +
                 "\"image\":\"14fd5b43-c405-4955-b3c8-601286653e0e\"," +
                 "\"title\":\"标题标题标题标题标题标题标题(06.26)上午推荐\"" +
                 "}" +



                 "]," +
                 "\"totalPage\":0," +
                 "\"total\":0" +
                 "}" +
                 "}" +
                 "}" +
                 "";


            }
            else if (Convert.ToInt64(sinceID) <=  472 && Convert.ToInt64(sinceID) >  467)
            {
                //第三页

                //第二页

                api = "" +
                 "{" +
                 "\"errorCode\":0," +
                 "\"message\":\"操作成功\"," +
                 "\"result\":{\"businessCode\":0," +
                 "\"message\":\"操作成功\"," +
                 "\"data\":{" +
                 "\"list\":[" +


                 "{" +
                 "\"newsId\":471," +
                 "\"releaseDate\":\"2017-05-24\"," +
                 "\"programaName\":\"标题标题\"," +
                 "\"image\":\"14fd5b43-c405-4955-b3c8-601286653e0e\"," +
                 "\"title\":\"标题标题标题标题标题标题标题标题标题(06.25)上午推荐\"" +
                 "}" +

                 "," +
                 "{" +
                 "\"newsId\":470," +
                 "\"releaseDate\":\"2017-05-24\"," +
                 "\"programaName\":\"快乐彩\"," +
                 "\"image\":\"14fd5b43-c405-4955-b3c8-601286653e0e\"," +
                 "\"title\":\"标题标题标题标题标题标题标题标题标题标题(06.26)上午推荐\"" +
                 "}" +

                 "," +
                 "{" +
                 "\"newsId\":469," +
                 "\"releaseDate\":\"2017-05-23\"," +
                 "\"programaName\":\"3D预测\"," +
                 "\"image\":\"ae8902c7-b7fe-4c0d-a9db-66300c1c8f0b\"," +
                 "\"title\":\"标题标题标题标题标题标题标题标题标题标题(06.25)上午推荐\"" +
                 "}" +

                 "," +
                 "{" +
                 "\"newsId\":468," +
                 "\"releaseDate\":\"2017-05-23\"," +
                 "\"programaName\":\"方案预测\"," +
                 "\"image\":\"ae8902c7-b7fe-4c0d-a9db-66300c1c8f0b\"," +
                 "\"title\":\"标题标题标题标题标题标题标题标题(06.26)上午推荐\"" +
                 "}" +

                 "," +
                 "{" +
                 "\"newsId\":467," +
                 "\"releaseDate\":\"2017-05-23\"," +
                 "\"programaName\":\"福利彩\"," +
                 "\"image\":\"a2780dd1-f2ac-439d-b229-c417186bebc3\"," +
                 "\"title\":\"标题标题标题标题标题标题标题标题(06.26)上午推荐\"" +
                 "}" +



                 "]," +
                 "\"totalPage\":0," +
                 "\"total\":0" +
                 "}" +
                 "}" +
                 "}" +
                 "";



            }
            // 这个MAXID是要用来判断下拉刷新的,如果没有新的数据,就不再加载了。。。


            else
            {
                // 

                api = "" +
                "{" +
                "\"errorCode\":0," +
                "\"message\":\"操作成功\"," +
                "\"result\":{\"businessCode\":0," +
                "\"message\":\"操作成功\"," +
                "\"data\":{" +
                "\"list\":[" +





                "]," +
                "\"totalPage\":0," +
                "\"total\":0" +
                "}" +
                "}" +
                "}" +
                "";
            }

            }

        }

        //api = "{\"errorCode\":0,\"message\":\"操作成功\"}";

        context.Response.ContentType = "text/plain";
        context.Response.ContentEncoding = Encoding.UTF8;
        context.Response.Charset = "UTF-8";

        context.Response.Write(api);
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

哈,因为也才入门Swift不久,写的代码有可能还很生鲜,大牛可以略过!不过,还是希望这篇文章可以帮到刚好有上拉下拉需求的人。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,937评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,503评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,712评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,668评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,677评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,601评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,975评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,637评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,881评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,621评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,710评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,387评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,971评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,947评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,189评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,805评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,449评论 2 342

推荐阅读更多精彩内容