SwiftでAFNetworkingを利用してJSONデータ取得の覚え書き。

2015年1月24日 Posted by PURGE

結構理論的にはわかっているが、いざソースを書いてみるとかなりハマる。
オプショナル型の制約を熟知していないと、むしろ面倒でバグを誘発するのではないか?

とりあえず、Qiitaに記載する前のドラフト版のソースコード。
エラーが発生しないように、エラーを避けるようなコードを記述しているので結構不安。

MyTableViewController.swift

import UIKit

struct Game {
    init(){}
    var seasonId:String?
    var gameName:String?
    var gameType:String?
    var homeTeamName:String?
    var awayTeamName:String?
    var homeTeamScore: String?
    var awayTeamScore: String?
}

class MyTableViewController: UITableViewController {

    required init(coder aDecoder: NSCoder) {
        self.gameData = Game()
        super.init(coder: aDecoder)
    }

    var gameData:Game
        
    override func viewDidLoad() {
        super.viewDidLoad()

        //リクエストデータ取得
        let manager:AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
        let serializer:AFJSONRequestSerializer = AFJSONRequestSerializer()
        manager.requestSerializer = serializer
        manager.GET("http://score-sheet.herokuapp.com/api/games/latest.json", parameters: nil,
            success: {(operation: AFHTTPRequestOperation!, responsObject: AnyObject!) in
                let responsDict = responsObject as Dictionary<String, AnyObject>
                
                //値取得
                var seasonId:Int = (responsDict["season_id"] as AnyObject?) as Int
                var gameName:String = (responsDict["game_name"] as AnyObject?) as String
                var gameType:Dictionary = (responsDict["game_type"] as AnyObject?) as Dictionary<String, AnyObject>
                var gameTypeName:String = (gameType["game_type"] as AnyObject?) as String
                var homeTeam:Dictionary = (responsDict["home_team"] as AnyObject?) as Dictionary<String, AnyObject>
                var awayTeam:Dictionary = (responsDict["away_team"] as AnyObject?) as Dictionary<String, AnyObject>
                var homeTeamName:String = (homeTeam["team_name"] as AnyObject?) as String
                var awayTeamName:String = (awayTeam["team_name"] as AnyObject?) as String
                var homeTeamScore = (responsDict["home_team_score"] as AnyObject?) as Int
                var awayTeamScore = (responsDict["away_team_score"] as AnyObject?) as Int
                
                //取得データ設定
                self.gameData.seasonId = String(seasonId)
                self.gameData.gameName = gameName
                self.gameData.gameType = gameTypeName
                self.gameData.homeTeamName = homeTeamName
                self.gameData.awayTeamName = awayTeamName
                self.gameData.homeTeamScore = String(homeTeamScore)
                self.gameData.awayTeamScore = String(awayTeamScore)
                
                //データリロード
                self.tableView.reloadData()

                //テーブルビュー作成
                let tableView = MyTableView(frame: self.view.frame, style: UITableViewStyle.Plain)
                tableView.delegate = self
                tableView.dataSource = self
                self.view.addSubview(tableView)
                
                //セル設定
                let xib = UINib(nibName: "MyTableViewCell", bundle: nil)
                tableView.registerNib(xib, forCellReuseIdentifier: "BfCell")
            },
            failure: {(operation: AFHTTPRequestOperation!, error: NSError!) in
                println("Error!!")
            }
        )
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return 5
    }
    
    //セルデータ設定
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("BfCell", forIndexPath: indexPath) as MyTableViewCell
        
        cell.seasonId?.text = self.gameData.seasonId
        cell.gameName?.text = self.gameData.gameName
        cell.gameType?.text = self.gameData.gameType
        cell.homeTeamName?.text = self.gameData.homeTeamName
        cell.awayTeamName?.text = self.gameData.awayTeamName
        cell.homeTeamScore?.text = self.gameData.homeTeamScore
        cell.awayTeamScore?.text = self.gameData.awayTeamScore
        
        return cell
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //let cell = tableView.dequeueReusableCellWithIdentifier("BfCell") as UITableViewCell
        //return cell.bounds.height
        return 100
    }
    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */
    
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です