gpt4 book ai didi

ios - JSON 未在 TableView 中加载

转载 作者:行者123 更新时间:2023-11-28 09:35:20 25 4
gpt4 key购买 nike

这是我的带有 TableView 的 View Controller

class HomeVC: UIViewController, UITableViewDelegate, UITableViewDataSource {    

private let myArray: NSArray = ["First", "Second", "Third"]
private var myTableView: UITableView!

var articles: [ArticleClass]? = []


override func viewDidLoad() {
super.viewDidLoad()

view.backgroundColor = UIColor.white
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "Home"

getData()

let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height

myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight - barHeight))
myTableView.dataSource = self
myTableView.delegate = self
myTableView.register(ArticleCell.self, forCellReuseIdentifier: "MyCell")

view.addSubview(myTableView)
myTableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
myTableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
myTableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
myTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

}


func getData() {

let theURL = URL(string: "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=34e81be767734526b224ac353b1378e8")
let task = URLSession.shared.dataTask(with: theURL!) { (data, response, error) in

if error != nil {

print(error)
return

} else {

self.articles = [ArticleClass]()

do {

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]

if let articlesFromJSON = json["Articles"] as? [[String: Any]] {

for articleOutOfJSON in articlesFromJSON {

let theArticle = ArticleClass()

if let title = articleOutOfJSON as? String, let author = articleOutOfJSON["author"] as? String, let desc = articleOutOfJSON["description"] as? String, let url = articleOutOfJSON["url"] as? String, let imageToURL = articleOutOfJSON["imageToURL"] as? String {

theArticle.theDescription = desc
theArticle.author = author
theArticle.imageURL = imageToURL
theArticle.url = url

}

//Putting the articleOutOfJSON into our array.
self.articles?.append(theArticle)

}

}

//Making the data be on the main thread.
DispatchQueue.main.async {

self.myTableView.reloadData()

}


} catch {

print(error)

}

}

}

task.resume()

}




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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! ArticleCell

cell.title.text = self.articles?[indexPath.item].headline
cell.theDesc.text = self.articles?[indexPath.item].theDescription
cell.author.text = self.articles?[indexPath.item].author
cell.theImageView.downloadImage(from: (self.articles?[indexPath.item].url)!)

return cell

}

func numberOfSections(in tableView: UITableView) -> Int {
return self.articles?.count ?? 0
}


}

这是我的表格 View 单元格。

class ArticleCell: UITableViewCell {

let title: UILabel = {
let label = UILabel()
label.text = "Title"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()

let theDesc: UILabel = {
let label = UILabel()
label.text = "TEXT TEXT TEXT TEXT TEXT TEXT"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()

let author: UILabel = {
let label = UILabel()
label.text = "Author"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()

let theImageView: UIImageView = {
let image = UIImageView()
image.backgroundColor = UIColor.purple
image.translatesAutoresizingMaskIntoConstraints = false
return image
}()

override func awakeFromNib() {
super.awakeFromNib()

contentView.addSubview(theImageView)
theImageView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 8).isActive = true
theImageView.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -146).isActive = true
theImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 30).isActive = true
theImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -26).isActive = true

contentView.addSubview(title)
contentView.addSubview(theDesc)
contentView.addSubview(author)

}

override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

// Configure the view for the selected state
}

}

这是我的数据模型。

class ArticleClass: NSObject {
var headline: String?
var theDescription: String?
var author: String?
var url: String?
var imageURL: String?
var publishingDate: Int?
}

我已尝试将 JSON 加载到我的 TableView 中,但它不起作用。我现在看不出我的代码有什么问题。如果您能提供帮助,我将不胜感激。我也在网上寻求帮助,但无法根据我遇到的问题获得任何帮助。

最佳答案

我推荐使用Decodable协议(protocol)来解析JSON。

首先你不需要继承自NSObject的类,一个struct就足够了。文章结构使用 JSON 键作为属性:

struct News : Decodable {
let status : String
let articles : [Article]
}

struct Article : Decodable {
let description: String?
let author: String?
let url: URL
let urlToImage: URL?
let publishedAt: Date
}

然后将数据源数组声明为非可选

var articles = [Article]()

然后解析JSON

func getData() {
let theURL = URL(string: "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=••••••••••••••••••••")
let task = URLSession.shared.dataTask(with: theURL!) { (data, response, error) in

if error != nil {
print(error!)
return
} else {
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let news = try decoder.decode(News.self, from: data!)
self.articles = news.articles

//Making the data be on the main thread.
DispatchQueue.main.async {
self.myTableView.reloadData()
}
} catch {
print(error)
}
}
}
task.resume()
}

您的代码中还有其他问题:

您混淆了 numberOfSectionsnumberOfRowsInSection。在 numberOfSections 中返回 1 或省略方法

func numberOfSections(in tableView: UITableView) -> Int {
返回 1
}

numberOfRowsInSection 中返回文章数

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

cellForRow 中使用 .row 而不是 .item

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! ArticleCell
let article = self.articles[indexPath.row]
cell.title.text = article.title
cell.theDesc.text = article.description
cell.author.text = article.author
cell.theImageView.downloadImage(from: article.url)
return cell
}

附言:

强烈建议您不要在公共(public)论坛上分享您的真实 API key 。更好的方法是发布 JSON 并对 key 进行乱码

关于ios - JSON 未在 TableView 中加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51185171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com