使用API中的JSON填充单元格 [英] Populate cells with JSON from API
问题描述
我有2个来自不同API的JSON.
I've got 2 JSON from different API.
这一项(活动):
{
"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"
}
]
里面有更多的活动和用户,但我删除了它们以缩短时间.
There a lot more activities and users inside but I removed them to make this shorter.
现在,目标是拥有这样的内容:示例.
Now, the goal would be to have something like this: example.
我已经设置了MainViewController
和MainViewControllerCell
MainViewController:
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
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.现在,我从未做过此事,所以我不知道哪种方法最好.
As you can see, I can already read the JSON. Now, I've never done this before so I don't know which is the best approach.
如何将Activity
中的userId
连接到Users
中的userId
?
How would I connect the userId
from Activity
to the userId
from Users
?
我如何将amount
,message
和化身连接到标签?
How would I connect the amount
, message
, and the avatars to the labels?
基本上如何使用JSON填充单元格以使其像示例一样?
Basically how do I populate the cells with the JSONs to have it like the example?
推荐答案
您可以这样实现:
在您的MainControllerViewCell
中为User
添加一个属性
in your MainControllerViewCell
add a property for 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
then in your MainTableViewController
you register the decoded users and reload the 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完成并且解码器工作时重新加载数据
you bind your userList to the TableView datasource, and you reload datas every time the URLSession is finished and the decoder worked
这篇关于使用API中的JSON填充单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!