使用Swift 4和Alamofire在UITableView中显示JSON数据

时间:2018-06-20 06:33:09

标签: json swift alamofire swift4

我是Swift的新手,请帮忙。我正在做一个快速解析JSON数据的应用程序,如下所示: Project 这是我编写的代码

import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{

    @IBOutlet weak var tableView: UITableView!

var albumArray = [AnyObject]()
    var url = ("https://jsonplaceholder.typicode.com/photos")

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.

                  Alamofire.request("https://jsonplaceholder.typicode.com/photos").responseJSON { (responseData) -> Void in
                if((responseData.result.value) != nil) {
                    let swiftyJsonVar = JSON(responseData.result.value!)
//
                    if let resData = swiftyJsonVar[].arrayObject {
                        self.albumArray = resData as [AnyObject]; ()

                    }
                    if self.albumArray.count > 0 {
                        self.tableView.reloadData()
                    }
                }
            }

        }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return albumArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? CostumTableViewCell

        let title = albumArray[indexPath.row]
        cell?.titleLabel?.text = title["title"] as? String

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


}

问题是没有任何错误,但不显示数据。您还可以看到JSON:https://jsonplaceholder.typicode.com/photos

1 个答案:

答案 0 :(得分:0)

您的相同代码对我有用。在主队列中重新加载,并确保您为单元格中的标签设置了约束。连接您的表视图的数据源和委托,然后检查。