2017-11-25 16 views
0

APIからデータをダウンロードしてTableViewControllerに表示しようとするとエラーが発生します。テーブルビューは空です。私はそれが間違っていることを理解していない。基本的に、私はこのタイプのエラーを取得しています:TableViewControllerためJSONデータが表示されない - エラーが発生する

2017-11-25 08:03:42.775803 ClassDesign[2243:51810] [] __nwlog_err_simulate_crash_libsystem libsystem simulate crash unavailable "libsystem_network.dylib: nw_host_stats_add_src :: received error for SRC_ADDED: [22] Invalid argument" 2017-11-25 08:03:42.776596 ClassDesign[2243:51810] [] nw_host_stats_add_src received error for SRC_ADDED: [22] Invalid argument, dumping backtrace: [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 Message from debugger: Terminated due to signal 15

私のコードは次のようになります。また、

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 
} 

} 
+0

レスポンスを取得した後、どこでテーブルビューデータをリロードしていますか? –

答えて

0

完了ハンドラの最後に、メインスレッドのテーブルビューをリロードする必要があります。

DispatchQueue.main.async { 
    self.tableView.reloadData() 
} 

// print(self.fetchedExercise[3].name) 

をコメントアウトされている行を交換し、あなたはデフォルトGETリクエストのURLリクエストもこの中に特定のセッションどちらを必要としません大文字と小文字の区別はありません。

ただし、これは問題とは関係ありません。

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

そして最後に

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

を交換してください - いつものように - jsonObject(with内のすべての.mutable...オプションは、スウィフトにナンセンスです。パラメータを省略します。

+0

メンバー 'dataTaskへのあいまいな参照'(with:completionHandler :) ' – Rvfvl

+0

はい、すべて私は' 'を言って' let task = URLSession.shared.dataTask(with:url){(data、response、error)あなたが私に言ったように、私はvar request、configuration、sessionをurlとtaskに置き換えました。しかし、私はURLの要求を維持する場合は正常に動作します。 – Rvfvl

+0

最新の回答をご覧ください。 – vadian

関連する問題