使用API​​中的JSON填充单元格

时间:2019-06-07 01:36:48

标签: ios json swift

我有2个来自不同API的JSON。

此(活动):

{
    "oldest": "2019-01-24T00:00:00+00:00",
    "activities": [
        {
            "message": "<strong>Henrik</strong> didn't resist a guilty pleasure at <strong>Starbucks</strong>.",
            "amount": 2.5,
            "userId": 2,
            "timestamp": "2019-05-23T00:00:00+00:00"
        },
        {
            "message": "<strong>You</strong> made a manual transfer.",
            "amount": 10,
            "userId": 1,
            "timestamp": "2019-01-24T00:00:00+00:00"
        }
    ]
}

这个(用户):

[
    {
        "userId": 1,
        "displayName": "Mikael",
        "avatarUrl": "http://qapital-ios-testtask.herokuapp.com/avatars/mikael.jpg"
    },
    {
        "userId": 6,
        "displayName": "Daniel",
        "avatarUrl": "http://qapital-ios-testtask.herokuapp.com/avatars/daniel.jpg"
    }
]

里面有更多的活动和用户,但我删除了它们以缩短时间。

现在,目标是拥有这样的东西:example

我已经设置了MainViewControllerMainViewControllerCell

MainViewController:

struct Activities: Decodable {
    let oldest: String
    let activities: [Activity]
}

struct Activity: Decodable {
    let message: String
    let amount: Float
    let userId: Int
    let timestamp: String
}

struct Users: Decodable {
    let avatarUrl: String
    let displayName: String
    let userId: Int
}

class MainTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

//        let userJSONURLString = "https://qapital-ios-testtask.herokuapp.com/users"
        let activitiesJSONURLString = "https://qapital-ios-testtask.herokuapp.com/activities?from=2016-05-23T00:00:00+00:00&to=2019-05-23T00:00:00+00:00"
//        guard let userURL = URL(string: userJSONURLString) else { return }
        guard let activitiesURL = URL(string: activitiesJSONURLString) else { return }

        URLSession.shared.dataTask(with: activitiesURL) { (data, response, err) in

            guard let data = data else { return }

            do {
                // Activities
                let activities = try JSONDecoder().decode(Activities.self, from: data)
                print(activities)

                // Users
//                let users = try JSONDecoder().decode([Users].self, from: data)
//                print(users)

            } catch let jsonErr {
                print("Error serializing json: ", jsonErr)
            }

        }.resume()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 0
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 0
    }

MainControllerViewCell

class MainTableViewCell: UITableViewCell {

    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var imgView: UIImageView!
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var amountLabel: UILabel!

    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
    }

}

如您所见,我已经可以读取JSON。现在,我从未做过此事,所以我不知道哪种方法最好。

如何将userId的{​​{1}}连接到Activity的{​​{1}}?

我如何将userIdUsers和头像连接到标签?

基本上如何使用JSON填充单元格,使其像示例一样?

1 个答案:

答案 0 :(得分:0)

您可以通过这种方式实现:

在您的MainControllerViewCell中为User添加一个属性

class MainTableViewCell: UITableViewCell {

    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var imgView: UIImageView!
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var amountLabel: UILabel!

    var user: User? {
        didSet {
            descriptionLabel.text = user?.displayName 
            // etc... you set your cell's outlets in accordance to `user`s infos
        }
    }
}

然后在您的MainTableViewController中注册已解码的用户并重新加载tableView

class MainTableViewController: UITableViewController {

    var userList: [User] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        let activitiesJSONURLString = "https://qapital-ios-testtask.herokuapp.com/activities?from=2016-05-23T00:00:00+00:00&to=2019-05-23T00:00:00+00:00"
        guard let activitiesURL = URL(string: activitiesJSONURLString) else { return }

        URLSession.shared.dataTask(with: activitiesURL) { (data, response, err) in

            guard let data = data else { return }

            do {
                // Activities
                let activities = try JSONDecoder().decode(Activities.self, from: data)
                print(activities)

                // Users
                let users = try JSONDecoder().decode([Users].self, from: data)
                userList = [] 
                userList.append(users)
                tableView.reloadData // reload 

            } catch let jsonErr {
                print("Error serializing json: ", jsonErr)
            }

        }.resume()
    }

    // MARK: - Table view data source

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        cell = dequeueReusableCell(withIdentifier: "MyCellIdentifier", for: indexPath) as! MainTableViewCell
        cell.user = userList[indexPath.row]
        return cell
    }
}

您将userList绑定到TableView数据源,并在每次URLSession完成并且解码器工作时重新加载数据