我在尝试从 API 下载数据并将其显示在 TableViewController 中时遇到错误。表视图为空。我不明白这有什么问题。基本上,我遇到了这种类型的错误:
2017-11-25 08:03:42.775803 ClassDesign [2243:51810] [] __nwlog_err_simulate_crash_libsystem libsystem 模拟崩溃不可用“libsystem_network.dylib:nw_host_stats_add_src ::收到SRC_ADDED错误:[22]无效参数” 2017-11-25 08:03:42.776596 ClassDesign[2243:51810] [] nw_host_stats_add_src 收到 SRC_ADDED 错误:[22] 参数无效,转储回溯: [x86_64] libnetcore-856.30.16 0 libsystem_network.dylib 0x0000000109060666 __nw_create_backtrace_string + 123 1 libsystem_network.dylib 0x00000001090772f6 nw_get_host_stats + 1083 2 libnetwork.dylib 0x0000000109356e9f nw_endpoint_resolver_start_next_child + 1382 3 libdispatch.dylib 0x0000000108ddd978 _dispatch_call_block_and_release + 12 4 libdispatch.dylib 0x0000000108e070cd _dispatch_client_callout + 8 5 libdispatch.dylib 0x0000000108de4e17 _dispatch_queue_serial_drain + 236 6 libdispatch.dylib 0x0000000108de5b4b _dispatch_queue_invoke + 1073 7 libdispatch.dylib 0x0000000108de8385 _dispatch_root_queue_drain + 720 8 libdispatch.dylib 0x0000000108de8059 _dispatch_worker_thread3 + 123 9 libsystem_pthread.dylib 0x00000001091ba1ca _pthread_wqthread + 1387 10 libsystem_pthread.dylib 0x00000001091b9c4d start_wqthread + 13 来自调试器的消息:由于信号 15 而终止
我的 TableViewController 代码是:
import UIKit
class ExerciseTableViewController: UITableViewController {
var fetchedExercise = [Exercise]()
override func viewDidLoad() {
super.viewDidLoad()
parseData()
}
func parseData() {
fetchedExercise = []
let url = "https://wger.de/api/v2/exercise/?format=json&language=2&status=2"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if error != nil {
print("Error while parsing JSON")
}
else {
do {
if let data = data,
let fetchedData = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String:Any],
let exercises = fetchedData["results"] as? [[String: Any]] {
for eachExercise in exercises
{
let name = eachExercise["name"] as! String
let description = eachExercise["description"] as! String
self.fetchedExercise.append(Exercise(name: name, description: description))
}
// print(self.fetchedExercise[3].name)
}
}
catch {
print("Error while parsing data.")
}
}
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return fetchedExercise.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "ExerciseCell", for: indexPath) as? ExerciseCell {
let exercise = fetchedExercise[indexPath.row]
cell.configureCell(exercise: exercise)
return cell
} else {
return UITableViewCell()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
我的自定义单元类中的“configureCell”函数的代码如下:
import UIKit
class ExerciseCell: UITableViewCell {
@IBOutlet weak var nameLbl: UILabel!
var exercise: Exercise!
func configureCell(exercise: Exercise) {
self.exercise = exercise
nameLbl.text = self.exercise.name
}
}
在完成处理程序结束时,您必须在主线程上重新加载表视图。
替换被注释掉的行
// print(self.fetchedExercise[3].name)
与
DispatchQueue.main.async {
self.tableView.reloadData()
}
在这种情况下,您既不需要默认
GET
请求的 URL 请求,也不需要特定会话,因为您不使用委托模式。
但这与问题无关。
更换
let url = "https://wger.de/api/v2/exercise/?format=json&language=2&status=2"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in ...
与
let urlString = "https://wger.de/api/v2/exercise/?format=json&language=2&status=2"
let url = URL(string: urlString)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in ...
最后 - 一如既往 -
.mutable...
中的所有 jsonObject(with
选项在 Swift 中都是无意义的。省略参数。