【发布时间】:2016-10-05 12:34:30
【问题描述】:
我正在尝试解析 json 并将其加载到 CustomTable 中,我的 json 解析成功但无法在 UI 中加载数据,我尝试添加测试数据并显示。所以我想这与范围界定有关。我曾尝试在同一个问题上使用其他答案,但它仍然不适合我
import UIKit
import Alamofire
import SwiftyJSON
class NewsViewController: UIViewController,
UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var newsPosts = [NewsPost]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
getNewsPost()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = newsPosts[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "NewsCell") as? NewsPostCell{
cell.configureCell(post: post)
return cell
}else{
let cell = NewsPostCell()
cell.configureCell(post: post)
return cell
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newsPosts.count
}
func getNewsPost(){
Alamofire.request(URL_BASE + NEWS_URL).responseJSON { response in
let json = JSON(data: response.data!)
if let dict = json.dictionaryObject{
if let result = dict["data"] as? [NSDictionary]{
for data in result{
guard let title = data["title"] as? String else{
return print("title is nil")
}
guard let href = data["href"] as? String else{
return print("href is nil")
}
guard let image = data["image"] as? String else{
return print("image is nil")
}
guard let content = data["content"] as? String else{
return print("content is nil")
}
guard let _ = data["timestamp"] as? String else{
return print("timestamp is nil")
}
guard let type = data["type"] as? String else{
return print("type is nil")
}
print(type)
let post = NewsPost(title: title, href: href,
image: image, timestamp:
"1 day ago", content: content, type: type)
self.newsPosts.append(post)
}
self.tableView.reloadData()
}
}
}
}
}
【问题讨论】:
-
你没有崩溃?当您在 'cellForRowAt indexPath' 中时,您是否尝试过记录 newPosts 中的内容?
-
我没有崩溃,我记录了 newPosts,但它什么也没显示,就像它没有到达那里。
-
这行 'print(type)' 是否记录想要的对象?
-
是的,这就是谜团,newsPosts 都在 forloop 中打印出它的值
-
您应该尝试在创建帖子后立即记录它,并在您添加条目后立即记录您的帖子数组
标签: json swift uitableview alamofire swifty-json