我正在尝试解析来自网站的数据,然后按下按钮将其显示到表格视图中。我正在使用 swift 3,Xcode 8.2 beta 并且无法将数据存储到数组中或显示到 tableView 中。这是我的 tableViewCell 类:
class TableViewCell: UITableViewCell {
@IBOutlet weak var userIdLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
这是我的视图控制器代码:
import UIKit
class SecondViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
let urlString = "https://jsonplaceholder.typicode.com/albums"
@IBOutlet weak var tableView: UITableView!
var titleArray = [String]()
var userIdArray = [String]()
@IBAction func getDataButton(_ sender: Any) {
self.downloadJSONTask()
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func downloadJSONTask() {
let url = NSURL(string: urlString)
var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
downloadTask.httpMethod = "GET"
URLSession.shared.dataTask(with: (url! as URL), completionHandler: {(Data, URLResponse, Error) -> Void in
let jsonData = try? JSONSerialization.jsonObject(with: Data!, options: .allowFragments)
print(jsonData as Any)
if let albumArray = (jsonData! as AnyObject).value(forKey: "") as? NSArray {
for title in albumArray{
if let titleDict = title as? NSDictionary {
if let title = titleDict.value(forKey: "title") {
self.titleArray.append(title as! String)
print("title")
print(title)
}
if let title = titleDict.value(forKey: "userId") {
self.userIdArray.append(title as! String)
}
OperationQueue.main.addOperation ({
self.tableView.reloadData()
})
}
}
}
}).resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return titleArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.titleLabel.text = titleArray[indexPath.row]
cell.userIdLabel.text = userIdArray[indexPath.row]
return cell
}
}