Json tableView 上没有显示数据

Json data not showing on tableView

我正在用 Swift 为 iOS 构建一个小部件。主要应用程序的目的是连接到 URL 新闻提要并获取最新消息,而小部件仅获取标题以显示在“今日”视图的 table 视图中。

我为小部件编写了此方法,以便获取填充 table 的数据,但由于某种原因没有显示任何内容。我试过调试它,但作为一个小部件,它似乎几乎不可能。

这是 cellForRowAt,我在其中连接到提要并尝试提取数据。有趣的是,主应用程序使用基本相同的代码并且运行完美。

     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)


      let urlRequest = URLRequest(url: URL(string: "https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=c64849bc30eb484fb820b80a136c9b0a")!)


      let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

           do{

                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]

                if let articlesFromJson = json["articles"] as? [[String: AnyObject]] {

                     if !(error != nil) {

                          var resultArray: NSMutableArray = NSMutableArray()

                          for articlesFromJson in articlesFromJson {

                               if let title = articlesFromJson["title"] as? String{
                                    resultArray.add(title)

                               }

                               let array:NSArray = resultArray.reverseObjectEnumerator().allObjects as NSArray
                               resultArray = array as! NSMutableArray
                               let title:String = resultArray.object(at: indexPath.row) as! String
                               cell.textLabel?.text = title

                          }
                     }            
                }

                //reload on main thread to speed it up
                DispatchQueue.main.async {
                 self.tableView.reloadData()
                }

           } catch let error {
                print(error)
           }            
      }
      task.resume()

      return cell
 }

如果有人能帮我找出错误所在,那将是一个巨大的帮助,我已经在这个问题上停留了好几天了。谢谢

您想在 cellForRow 之外发出网络请求,然后在完成后重新加载数据,让 tableView 重新加载调用 cellForRow 的单元格。

在请求之外存储数据数组,以便您可以从函数外部引用它。

var resultArray: NSMutableArray = []

override func viewDidLoad() {
   super.viewDidLoad()
   getData()
 }     

func getData() {
  let urlRequest = URLRequest(url: URL(string: "https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=c64849bc30eb484fb820b80a136c9b0a")!)

  let task = URLSession.shared.dataTask(with: urlRequest) {[weak self] (data,response,error) in
    guard let strongSelf = self else { return }
    do{
        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
        if let articlesFromJson = json["articles"] as? [[String: AnyObject]] {
            if error == nil {
                for articlesFromJson in articlesFromJson {
                    if let title = articlesFromJson["title"] as? String{
                        strongSelf.resultArray.add(title)
                    }
                    let array:NSArray = strongSelf.resultArray.reverseObjectEnumerator().allObjects as NSArray
                    strongSelf.resultArray = array as! NSMutableArray

                    DispatchQueue.main.async {
                        strongSelf.tableView.reloadData()
                    }

                } catch let error {
                    print(error)
                }            
            }
            task.resume()
     }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

  let title:String = resultArray.object(at: indexPath.row) as! String

  cell.textLabel?.text = title

  return cell
}
checks proper if TableView delegate or datasource proper connected. and check array count before load data in cell 
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if (resultArray.count > 0){
      let title:String = resultArray.object(at: indexPath.row) as! String

  cell.textLabel?.text = title
}
else
{
  print("Error: resultArray contain nil value ")
}


  return cell
}