json - swift 3.0 : tableview cannot show data which received as JSON through web api

标签 json swift tableview

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

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    

    }
}

谁能帮我看看?

最佳答案

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

关于json - swift 3.0 : tableview cannot show data which received as JSON through web api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42001693/

相关文章:

Swift:解析服务器登录facebook无法检索邮件

ios - 如何防止细胞周转效应?

ios - 如何将一行从 TableView 滑动到另一个

ios - tableView 滚动到底部不显示最后一部分,必须手动滚动,有人知道吗?

java - Json 到 kotlin 数据类

java - Jackson Deserializer 委托(delegate)给下一个适用的反序列化器

swift - 如何在 HTTP 请求正文中发送 '&' 字符?

javascript - 使用 JSON 中的属性之一查找子对象

javascript - 如何将此 JSON 从 PHP 转换为 Javascript 数组

swift - 在 Swift2 中如何解决这个错误?