【发布时间】:2017-06-22 11:52:08
【问题描述】:
我是 Swift 新手,正在学习如何将 JSON 数据下载到表格视图中。该代码在编译时不会显示任何错误,但会在运行时显示。 JSON数据链接:https://jsonplaceholder.typicode.com/comments
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! show
let loadingInBackground = DispatchQueue(label: "loadingInBackground", qos: .background)
loadingInBackground.async {
let stringURL = "https://jsonplaceholder.typicode.com/comments"
let urlFromString = URL(string: stringURL)
var request = URLRequest(url: urlFromString!)
request.httpMethod = "GET"
let session = URLSession(configuration: URLSessionConfiguration.default)
session.dataTask(with: request) { (data, response, error) in
do {
let dataInJSON = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [ [String: Any] ]
print(dataInJSON)
let arrayOf_dataInJSON = dataInJSON[indexPath.row]
cell.id.text = arrayOf_dataInJSON["id"] as! String?
cell.email.text = ("email: \(arrayOf_dataInJSON["email"] as! Int?)")
}catch{print(error)}
}.resume()
}
return cell
}
}
class show : UITableViewCell {
@IBOutlet var id: UILabel!
@IBOutlet var email: UILabel!
}
错误是:“无法将 '__NSCFNumber' (0x10e7c1540) 类型的值转换为 'NSString' (0x10b679c40)”
我收到错误:“cell.id.text = arrayOf_dataInJSON["id"] as!String?”
【问题讨论】:
-
"id": 1是一个数字,你将它强制转换为一个字符串,除了崩溃,你期望发生什么? -
请告诉我如何解决这个问题@luk2302
-
好吧,我是这个@NiravD 的新手。
-
@RajeevKulariya 试试这个
cell.id.text = "\(arrayOf_dataInJSON["id"] as? Int ?? 0)"
标签: swift