非入門篇:服務器后端+MJRefresh第三方庫的上拉刷新與下拉刷新

此篇非入門篇虱黄,入門請簡友移步 http://www.hangge.com/blog/cache/search.php?key=Mjrefresh

看似簡單的下拉魔种,上拉,其實還蠻復雜的,值得好好研究!

寫在貼代碼之前荷荤,首先得思考幾個問題:
1、下拉時得查找服務器上最新的數(shù)據 然后填充Model
2梭稚、再次下拉時,查找服務器上是否再有新的數(shù)據了,有的話再把新的加在數(shù)組在前面
3伸辟、不要每次下拉都清空Model,再把下拉的數(shù)據都填充到Model恰梢,試想想埂陆,如果用戶本來已經上拉了500條數(shù)據在手機里,你再一下拉蓬抄,豈不是把用戶本機上的都清空了胆敞?(一定要和后臺配合好秦叛,通過MaxID值或者其它值來判斷)
4膨报、上拉時饮怯,相對簡單點闰靴,有新的數(shù)據识埋,就直接把新的數(shù)據加在數(shù)組的后面就行了,沒有的話蛹疯,就提示用戶沒有再多數(shù)據就可以了。

話嘮嗑多了,直接上代碼了邻吭,MVVC+服務器后端JSON 共5個文件!
一淫痰、MODEL

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

import UIKit
import HandyJSON

// 有用的數(shù)據才建立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 時 待優(yōu)化 -- 已優(yōu)化 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]()

    // 加載數(shù)據
    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)
        // 最新數(shù)據
        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 ("沒有更多的數(shù)據了")
                    completion(false)    
                }
  
            } else {
                
                // 下拉刷新 如果有最新數(shù)據newsDataModel.list,則把數(shù)據放在數(shù)組在前面
                
                if self?.newsDataModel.list?.count != 0 { 
                    self?.newsList = (self?.newsDataModel.list!)! + (self?.newsList)!
                    completion(true)
                }else {
                    print ("已經是最新數(shù)據了")
                    completion(true)
                }
            }
            print ("是否\(isPullUp)上拉刷新,共刷新到:\((self?.newsDataModel.list?.count) )條數(shù)據")
       }
    }
}

四朗鸠、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
        }
        // 加載數(shù)據
        initData(maxID:maxID,sinceID:sinceID,isPullUp: false)
        // 刷新數(shù)據
        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: - 刷新數(shù)據
    func initRefresh(){
        // MARK: - 下拉刷新
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            // SVProgressHUD.show(withStatus: "加載數(shù)據中")
            // 表示下拉刷新
            self?.isPullUp = false
            // 取得數(shù)組中的最大的ID烛占,傳給服務器,如果也是最大的ID沟启,則服務器就返回 空數(shù)組 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: "加載更多數(shù)據")
            // 表示上拉刷新
            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
    }
    
    // 加載數(shù)據
    func initData(maxID:Int64,sinceID:Int64,isPullUp:Bool) {
        print ("**********" ,isPullUp , "**********")
        // 把 數(shù)據加載 都放在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
            {
            // 這個要判斷是否沒有更多的數(shù)據了
            //  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: - 單元格動態(tài)變化 
   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.請求數(shù)據
        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";   // 每一頁共顯示多少條數(shù)據
        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 ,如果有值筷转,則返回更多數(shù)據

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

        // SQL MAX ID 數(shù)據庫當中最大的ID,即為最新數(shù)據 

        // simulate real data 

        // 第一次加載數(shù)據 



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

        {
            // 初始API 第一頁 10 條數(shù)據
            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(數(shù)據庫的ID) > maxID 最大值,如果有則有數(shù)據悬而,如果沒有則返回無數(shù)據呜舒,則表示下拉刷新
            if (Convert.ToInt64(maxID) == 481 )
            {
                // 表示是下拉刷新,但是從 iOS客戶端獲得的 maxID = 481 為數(shù)據庫當中最大的了 ...

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





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

            else
            {

            // 這邊要從數(shù)據庫讀出 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是要用來判斷下拉刷新的,如果沒有新的數(shù)據般婆,就不再加載了到腥。。蔚袍。


            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不久,寫的代碼有可能還很生鮮页响,大怕ㄗ悖可以略過!不過闰蚕,還是希望這篇文章可以幫到剛好有上拉下拉需求的人栈拖。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市没陡,隨后出現(xiàn)的幾起案子涩哟,更是在濱河造成了極大的恐慌索赏,老刑警劉巖,帶你破解...
    沈念sama閱讀 210,914評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件贴彼,死亡現(xiàn)場離奇詭異潜腻,居然都是意外死亡,警方通過查閱死者的電腦和手機器仗,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,935評論 2 383
  • 文/潘曉璐 我一進店門融涣,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人精钮,你說我怎么就攤上這事威鹿。” “怎么了轨香?”我有些...
    開封第一講書人閱讀 156,531評論 0 345
  • 文/不壞的土叔 我叫張陵忽你,是天一觀的道長。 經常有香客問我臂容,道長科雳,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,309評論 1 282
  • 正文 為了忘掉前任脓杉,我火速辦了婚禮糟秘,結果婚禮上,老公的妹妹穿的比我還像新娘丽已。我一直安慰自己蚌堵,他們只是感情好,可當我...
    茶點故事閱讀 65,381評論 5 384
  • 文/花漫 我一把揭開白布沛婴。 她就那樣靜靜地躺著吼畏,像睡著了一般。 火紅的嫁衣襯著肌膚如雪嘁灯。 梳的紋絲不亂的頭發(fā)上泻蚊,一...
    開封第一講書人閱讀 49,730評論 1 289
  • 那天,我揣著相機與錄音丑婿,去河邊找鬼性雄。 笑死,一個胖子當著我的面吹牛羹奉,可吹牛的內容都是我干的秒旋。 我是一名探鬼主播,決...
    沈念sama閱讀 38,882評論 3 404
  • 文/蒼蘭香墨 我猛地睜開眼诀拭,長吁一口氣:“原來是場噩夢啊……” “哼迁筛!你這毒婦竟也來了?” 一聲冷哼從身側響起耕挨,我...
    開封第一講書人閱讀 37,643評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后肌幽,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 44,095評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡蜘犁,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,448評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了止邮。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片这橙。...
    茶點故事閱讀 38,566評論 1 339
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖农尖,靈堂內的尸體忽然破棺而出析恋,到底是詐尸還是另有隱情,我是刑警寧澤盛卡,帶...
    沈念sama閱讀 34,253評論 4 328
  • 正文 年R本政府宣布,位于F島的核電站筑凫,受9級特大地震影響滑沧,放射性物質發(fā)生泄漏。R本人自食惡果不足惜巍实,卻給世界環(huán)境...
    茶點故事閱讀 39,829評論 3 312
  • 文/蒙蒙 一滓技、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧棚潦,春花似錦令漂、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,715評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至妹窖,卻和暖如春纬朝,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背骄呼。 一陣腳步聲響...
    開封第一講書人閱讀 31,945評論 1 264
  • 我被黑心中介騙來泰國打工共苛, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蜓萄。 一個月前我還...
    沈念sama閱讀 46,248評論 2 360
  • 正文 我出身青樓隅茎,卻偏偏與公主長得像,于是被迫代替她去往敵國和親嫉沽。 傳聞我的和親對象是個殘疾皇子辟犀,可洞房花燭夜當晚...
    茶點故事閱讀 43,440評論 2 348

推薦閱讀更多精彩內容