2016-10-14 3 views
-1

テーブルビューにデータを読み込む際に問題があります。データが正しく読み込まれないようです。私はちょうどIOSプログラミングに着手し始めており、しばらくの間この問題に取り組んできました。これらのコードで空のTableviewを取得するのはなぜですか? JSON

Here is a screenshot of my storyboard

override func viewDidLoad() { 
    super.viewDidLoad() 
} 

var afspraken = [Afspraak]() 

func loadJsonData() 
{ 
    let url = URL(string: "https://i342444.venus.fhict.nl/") 
    let dataTask = URLSession.shared.dataTask(with: url!) 
    { 
     (data, response, error) 
     in 
     if error != nil 
     { 
      print (error) 
     } 
     else 
     { 
      do 
      { 
       let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) 
       self.parseJsonData(jsonObject as! Array<AnyObject>) 
       print(data) 
      } 
      catch let error as NSError {print("Error parsing JSON: \(error)")} 
     } 
    } 

    dataTask.resume() 
} 

func parseJsonData(_ jsonObject: Array<AnyObject>) { 
    for item in jsonObject 
    { 
     let afspraak = 
      Afspraak(naam: item["naam"] as! String 
       , adres: item["adres"] as! String 
       , postcode: item["postcode"] as! String 
       , woonplaats: item["woonplaats"] as! String 
       , telefoonnummer: item["telefoonnummer"] as! String 
       , email: item["email"] as! String 
       , datum: item["datum"] as! Date 
       , tijdstip: item["tijdstip"] as! String 
       , omschrijving: item["omschrijving"] as! String) 


     afspraken.append(afspraak) 
    } 
    self.tableView.reloadData() 
} 

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return afspraken.count 
} 

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{ 
    let Cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 
    let currentRow = indexPath.row 
    let currentAfspraak = self.afspraken[currentRow] 
    Cell.textLabel?.text = currentAfspraak.naam 
    return Cell 
} 

答えて

0

アンURLDataTaskリクエストは、バックグラウンドスレッド(非UIスレッド)で実行されています。したがって、完了後にGCD-Grand Central Dispatchを使用してメインスレッドのUIを更新する必要があります。

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

編集

私はあなたのJSONのURLに見ていた、それはHTMLファイルで、JSONファイルではありません。そのため、JSONSerializationが無効になっています。 json文字列をHTMLファイルに埋め込むのではなく、.jsonファイルをサーバーに配置する必要があります。あなたは、これはHTMLで見ることができるよう as you can see this is an HTML.

サーバー上のファイルは次のようです。

正しいJSONファイルは次のようにする必要があります: enter image description here

は、画像の上に2つのURLの違いを注意してください、正しいものは.jsonを持っており、あなたがある、ちょうど/ありますディレクトリ。

は、したがって、あなたが何をする必要があるかhttps://i342444.venus.fhict.nl/coolName.json

+0

真のように、これは私はまだ追加するために必要なものだった、あなたのサーバーにJSONファイルをアップロードし、対応するURLを使用しています。しかし、問題は、JSONデータの読み込みにあるようです。私の配列はコードを実行している間は空のままなので、何かが間違っていると私はそれをやめます。 –

+0

@DennisvdEijnde私の編集した回答をご覧ください。あなたのURLに問題があります。 –

関連する問題