这是我第一次在这里发布信息,也是我第一次练习解析json。非常抱歉,如果这篇文章有什么问题
我试图在Json中获取标题,描述和imageUrl,并将其附加在newsList数组中。我已经将它们追加到parseURL()函数内部,但是当我在parseURL()函数外部调用newsList数组时,里面没有任何内容
NewsList.swift
import UIKit
class NewsListVC: UIViewController {
@IBOutlet weak var newsTableView: UITableView!
var newsList: [News] = []
var newstitle: String!
var newsimage: String!
var newsdescription: String!
override func viewDidLoad() {
super.viewDidLoad()
print(parseURL())
newsTableView.delegate = self
newsTableView.dataSource = self
}
}
extension NewsListVC {
func parseURL() -> [News] {
let theURL =
"https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=mykey"
let url = URL(string: theURL)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
if error != nil {
print("didn't work")
} else {
//this will try to present the keys and values inside json dictionary
do {
//this will take the json that has a value of string and any value and store it in parseData
let parseData = try JSONSerialization.jsonObject(with: data!) as! [String: Any]
for (key, value) in parseData {
if (key == "articles") {
if let articleArray:[ [String:Any] ] = value as? [ [String:Any] ] {
//this will loop through all articles
for dict in articleArray {
for (key, value) in dict {
if (key == "urlToImage") {
self.newsimage = value as? String
} else if (key == "title") {
self.newstitle = value as? String
} else if (key == "description") {
self.newsdescription = value as? String
}
}
self.newsList.append(News(title: self.newstitle, image: self.newsimage, description: self.newsdescription))
print(self.newsList[self.newsList.count - 1].title!)
}
}
}
}
} catch let error as NSError {
print(error)
}
}
}.resume()
return self.newsList
}
}
News.swift
struct News {
var title: String!
var image: String!
var description: String!
init(title: String, image: String, description: String) {
self.title = title
self.image = image
self.description = description
}
}
我只想获取json并将其附加到数组中,以便可以在tableviewcell标签和imageView中分配数组的值。