LoginSignup
18
20

More than 5 years have passed since last update.

[swift] SwiftyJSONをつかって、JSONの値をUITableViewに表示

Last updated at Posted at 2015-03-02

今日1日JSONの読み込みに手こずってしまった。
まだまだ、Swiftに慣れななぁ〜

こんなにかかってしまったのは、「楽しいプログラミング」に書かれているJSONの読み込みのコードが、あまりにも不安定で原因がわからない状態だった。
その後、SwiftyJSONを試してみたが、TableViewに表示するのがわからなかった。
しかし、こちらのサイトを見つけて参考になりました。
"[Swift]APIで取得したJSONをswiftyJSONでパースして、天気情報をUITableViewで表示。お天気アプリを作ってみる。"

ViewController.swift
import UIKit

class ViewController: UITableViewController {
    // セクションの数
    let sectionNum = 1
    // 1セクションあたりのセルの行数
    let cellNum = 5
    let urlString = "~" //適当なjsonファイルへのパス
    // セルの中身
    var cellItems = NSMutableArray()
    // ロード中かどうか
    var isInLoad = false
    // 選択されたセルの列番号
    var selectedRow: Int?

    // ビューのロード完了時に呼ばれる
    override func viewDidLoad() {
        super.viewDidLoad()
        // json取得->tableに突っ込む
        makeTableData()
    }

    // json取得->tableに突っ込む
    func makeTableData() {
        self.isInLoad = true
        var url = NSURL(string: self.urlString)!
        var task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {data, response, error in
            // リソースの取得が終わると、ここに書いた処理が実行される
            var json = JSON(data: data)

            println(json["list"])
            // 各セルに情報を突っ込む
            //適当なJSONファイルが持っている値
            for var i = 0; i < self.cellNum; i++ {
                var hId = json["list"][i]["humanId"]  
                var aoutName = json["list"][i]["aouther"]
                var tId = json["list"][i]["titleId"]
                var titleName = json["list"][i]["title"]
                var info = "\(hId), \(aoutName), \(tId), \(titleName)"
                self.cellItems[i] = info
                println(hId)
            }
            // ロードが完了したので、falseに
            self.isInLoad = false
        })
        task.resume()

        while isInLoad {
            usleep(10)
        }
    }


    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return self.sectionNum
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //return titleName.count
        return self.cellNum
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("list", forIndexPath: indexPath) as UITableViewCell

        cell.textLabel?.text = self.cellItems[indexPath.row] as? String
        return cell
    }
    override func tableView(tableView: UITableView?, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        performSegueWithIdentifier("detail", sender: nil)
    }

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


}

JSON自体にも慣れておらず、うーん、、、、
SwiftyJSON自体もよくわからなかった。今更で、当たり前のことなんだけど、JSONの各値をイニシャライズしないとうまく動かない。
いろいろと大変だ。

18
20
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
20