swiftでのapi通信処理を共通化する方法 - UITableView編

はじめに

swiftでのapi通信処理を共通化する方法 - とりあえずphpとか
こちらの続きです。前回は画面が表示されるときに、APIを叩いて通信が完了したらviewを画面に追加する。というのものでした。

今回はアプリでよくある無限スクロールみたいのを実装します。
UITableViewの1番下までスクロールしたらAPIをたたいて、UITableViewに追加して再描画。という流れになるかと思います

実装方法

SampleViewController.swif

import UIKit
import Alamofire

class SampleViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var tableView: UITableView! // テーブルビュー
    var tableData: [AnyObject]! // テーブルデータ
    var isLoading:Bool = false // 読み込み中フラグ
    var objApi = ApiSample() // APIクラス
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // テーブルデータ初期化
        tableData = [AnyObject]()
        
        // データ取得
        self. objApiSample.get(callbackApi)
        
        // テーブルビュー追加
        tableView = UITableView(frame: CGRect(x:0, y:0, width:displayWidth, height:displayHeight))
        tableView.registerClass(UiTableViewCell.self, forCellReuseIdentifier: "Cell")
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)
    }

    // ・・・ おきまりのテーブルビューのデリゲートメソッドは省略します

    // テーブルの最下部までスクロールされたときの処理を実装します
    func scrollViewDidScroll(scrollView: UIScrollView) {
        var contentOffsetWidthWindow = self.tableView.contentOffset.y + self.tableView.bounds.size.height
        var eachToBottom = contentOffsetWidthWindow >= self.tableView.contentSize.height
        if (!eachToBottom || self.isLoading) {
            return;
        }
        self.isLoading = true
        self.objApiSample.get(callbackApi)
    }

    // コールバックメソッドを実装します
    func callbackApi() {
        if let list = self.objApi.result["data"] as? Array<Dictionary<String,AnyObject>> {
            for row in list {
                self.tableData.append(row)
            }
        }
        self.isLoading = false
        self.tableView.reloadData()
    }

ApiSampleクラスは前回と同じものを使ったのでこちらを参考にしてください。

以上です