【问题标题】:swift 3.0: tableview cannot show data which received as JSON through web apiswift 3.0:tableview 无法显示通过 web api 作为 JSON 接收的数据
【发布时间】:2017-02-02 11:59:45
【问题描述】:

我开始使用swift 3.0学习IOS开发。我构建了一个简单的应用程序来调用web api从服务器数据库中查询数据。我可以获取 json 数据并将其解析为字符串数组。应用程序可以打印数组,但不能在表格视图中显示。它让我困惑了几天,我在互联网上搜索了一些示例和答案,但仍然无法解决。 我的代码如下:

class LocationTableViewController: UITableViewController {

var names: [String] = []  

override func viewDidLoad() {
    super.viewDidLoad()

    //——————————————————————————get the data from web api and using json parsing————————————————————————
    let config = URLSessionConfiguration.default // Session Configuration
    let session = URLSession(configuration: config) // Load configuration into Session
    let url = URL(string: "http://XXXXXXX/api/mylocations")!

    let task = session.dataTask(with: url, completionHandler: {
        (data, response, error) in            
        if error != nil {                
            print(error!.localizedDescription)                
        } else {                
            do {                    
                var jsonResult: NSMutableArray = NSMutableArray()
                let jsonArray = try JSONSerialization.jsonObject(with: data!, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
                jsonResult = jsonArray.mutableCopy() as! NSMutableArray                    
                var jsonElement: NSDictionary = NSDictionary()                    

                for i in 0..<jsonResult.count {                        
                    jsonElement = jsonResult[i] as! NSDictionary                  
                    if let name = jsonElement["Name"] as? String                       
                    {
                        //  print(id)
                        //  print(name)
                        //  print(address)
                        // print(latitude)
                        // print(longitude)
                        // print("-------")
                        self.names.append(name)
                    }                                                
                    // self.tableView.reloadData()
                    // print(self.names)
                }                    
              print(self.names)
               // can print the string array data like [“name1”,”name2”,”name3”]                    
            } catch {                    
                print("error in JSONSerialization")                    
            }
        }            
    })

    task.resume()        
    //-------------- ———  result is [] it seems the above code didn't put the string array to names.——————————————
    print(self.names)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

override func numberOfSections(in tableView: UITableView) -> Int {
          return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return names.count;
}

internal override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
    UITableViewCell {
    let cellIdentifier = "cell"
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for:
    indexPath as IndexPath) as UITableViewCell
        // Configure the cell...
    cell.textLabel?.text = names[indexPath.row]
   return cell    

    }
}

谁能帮我看看?

【问题讨论】:

  • 请把贴出来的代码清理一下,去掉所有注释掉的代码,没用的didReceiveMemoryWarning,少空行,方便读者阅读

标签: json swift tableview


【解决方案1】:

self.tableView.reloadData() 放在打印print(self.names) 之后。

【讨论】:

  • 我试过 put self.tableView.reloadData() 但还是不行。谢谢!
  • @user7505698 尝试在主线程上重新加载 tableView。 DispatchQueue.main.async { self.tableView.reloadData() }
  • 主队列上的这个是解决方案
  • 非常感谢@NiravD!现在使用您的建议效果很好。
  • @user7505698 欢迎朋友 :)
【解决方案2】:

在你发表评论的地方......

result is [] 看来上面的代码没有把字符串数组放到 名字

这行代码数据在完成处理程序中下载之前被执行,所以我们不希望在这里看到任何东西。您会注意到它正在处理您在完成处理程序中拥有的其他打印。

完成处理程序末尾的tableView.reloadData() 应该可以工作。

您确定为 tableView 正确设置了代表吗?把下载任务注释掉,简单设置一下,会看到什么

names = ["Tom", "Dick", "Harry"]

viewDidLoad 内?如果这不起作用,那就是代表的问题。

【讨论】:

    猜你喜欢
    • 2015-08-17
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    相关资源
    最近更新 更多