【发布时间】:2017-01-02 18:37:31
【问题描述】:
我创建了一个 tableView,我想使用此链接在其中放置新闻
https://api.sis.kemoke.net/news
我想要获取并填充表格中的三件事。
String title
String text
String link
这是我的课
import Alamofire //Framework for handling http requests
import UIKit
/一个类,它将处理 http 请求,以字符串形式接收新闻,并用这些数据填充数组,这些数据将显示在一个表格中/ 类 NewsTableViewController: UITableViewController {
//Array which holds the news
var newsData:Array< String > = Array < String >()
// Download the news
func downloadData() {
Alamofire.request("https://api.sis.kemoke.net/news").responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
//Optional binding to handle exceptions
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
downloadData()
extractData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
// Number of sections i table vie
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newsData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = newsData[indexPath.row]
return cell
}
// Extract the data from the JSON
func extractData() {
Alamofire.request("https://api.sis.kemoke.net/news").responseJSON { response in
debugPrint(response)
if let json = response.result.value {
print("JSON: \(json)")
self.newsData = json as! Array
}
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
}
稍后我也会尝试获取图像,但现在这三个变量应该足够了。
【问题讨论】:
-
为什么你有两种方法(
extractData和downloadData)都做同样的事情?为什么都从viewDidLoad调用?为什么其中任何一个都不重新加载表格? -
@rmaddy 我认为有必要从 viewDidLoad 调用它们。这是由于我缺乏经验,因为我是移动应用程序开发的新手。请您解释一下如何解决我的问题?
标签: ios json swift tableview alamofire