【问题标题】:parsing data into tableview swift 3将数据解析为tableview swift 3
【发布时间】:2017-01-24 21:17:28
【问题描述】:

我正在尝试解析来自网站的数据,然后按下按钮将其显示到表格视图中。我正在使用 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
}

这是我的 viewController 代码:

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
    }
    }

【问题讨论】:

    标签: json uitableview swift3 xcode8-beta2


    【解决方案1】:

    你的代码有很多很多问题,最糟糕的是在 Swift 中使用NSArray/NSDictionary

    JSON是一个字典数组,键title的值是StringuserID的值是Int,所以你必须声明你的数组

    var titleArray = [String]()
    var userIdArray = [Int]()
    

    永远不要将 JSON 数据转换为大多数未指定的 Any,这是另一个禁忌。始终将其转换为实际类型。另一个大问题是闭包中的Data 参数与Swift3 中的本机结构冲突。使用 always 小写参数标签。您的代码中根本没有使用该请求。在 Swift 3 中,始终使用原生结构 URLDataURLRequest 等。最后,.allowFragments 是无稽之谈,因为 JSON 显然以集合类型开头。

    let url = URL(string: urlString)!
    let request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 20)
    URLSession.shared.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print(error!)
            return
        }
    
        do {
            if let jsonData = try JSONSerialization.jsonObject(with:data!, options: []) as? [[String:Any]] {
                print(jsonData)
                for item in jsonData {
    
                    if let title = item["title"] as? String {
                        titleArray.append(title)
                    }
                    if let userID = item["userId"] as? Int {
                        userIdArray.append(userID)
                    }
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                }
            }
        } catch let error as NSError {
            print(error)
        }
    }.resume()
    

    PS:使用两个单独的数组作为数据源也很糟糕。想象一下,其中一个可选绑定可能会失败,并且数组中的项目数会有所不同。这对运行时崩溃来说是一个很好的邀请。

    【讨论】:

    • 感谢您的帮助。我迷失了(如您所见),试图弄清楚如何将数据正确加载到单元格中。非常感谢你的帮助。当我将数据加载到单元格中时,我在这一行收到错误:“无法将 Int 的值分配给字符串类型”的“cell.userIdLabel.text = userIdArray[indexpath.row]”。有没有办法将 Int 加载到单元格文本标签中?
    • 如果您不再需要Int 类型,请将userIdArray 声明为[String] 并填充数组userIdArray.append("\(userID)")
    • 再次感谢您!这个项目是学习经验,您的帮助是无价的。我是应用程序开发的新手,我会听从您的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多