我是Swift的新手,无法找到正确的决定,如何修改我的代码以在我的TableView中显示JSON数据?我正在使用Alamofire,SwiftyJSON,Realm。
JSON:
object {4}
status : ok
source : techcrunch
sortBy : latest
articles [10]
0 {6}
author : Darrell Etherington
title : Tesla to triple service capability with repair fleet and service center expansion
description : Tesla is adding over 100 new service centers around the world, and putting over 350 new mobile service vans to work with its roaming fleet for house and work..
url : https://techcrunch.com/2017/07/11/tesla-to-triple-service-capability-with-repair-fleet-and-service-center-expansion/
urlToImage : https://tctechcrunch2011.files.wordpress.com/2017/07/serviceentrance.jpg?w=764&h=400&crop=1
publishedAt : 2017-07-11T13:21:09Z
1 {6}
2 {6}
3 {6}
4 {6}
5 {6}
6 {6}
7 {6}
8 {6}
9 {6}
我的代码如下:
领域:
class ArtFiles: Object {
dynamic var title: String = ""
}
Alamofire + JSON:
class ArticlesData {
func loadNews (title: String) {
let firstURL = "https://newsapi.org/v1/articles?source=techcrunch&sortBy=latest&apiKey=6b7c247d75914da0b7a53c8bb951c279"
let realm = try! Realm()
Alamofire.request(firstURL, method: .get).validate().responseJSON { response in
switch response.result {
case .success(let myValue) :
let myJSON = JSON(myValue)
let latestArticles = ArtFiles()
latestArticles.title = myJSON["articles"]["title"].stringValue
try! realm.write {
realm.add(latestArticles)
} case .failure(let error):
print(error)
}
}
}
}
使用结果:
在ViewController上工作class ArticlesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var artArray : [String] = []
let articlesData: ArticlesData = ArticlesData()
override func viewDidLoad() {
super.viewDidLoad()
print(Realm.Configuration.defaultConfiguration.fileURL)
for uploadArticles in artArray {
articlesData.loadNews(title: uploadArticles)
}
self.tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return artArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as? CustomTableViewCell
cell?.titleLabel?.text = artArray[indexPath.row]
return cell!
}
}
我看到一个空行。无法理解,如何使用我的决定将JSON数据添加到数组中。很高兴你的答案!