2015-09-27 49 views
0

我有一個tableview。 cekilecek_data包含tableview數據。我從JSON獲取一些數據,我想將這些數據附加到tableview。但我必須在jsonGetir()之內這樣做。但是,它不起作用。 kodJSONkodlarJSONviewDidLoad()中爲零。另外,cekilecek_data.append(kodJSON[1])它不會將數據添加到表中。在Swift中,更改函數在外部不起作用

我該如何解決?

var cekilecek_data = ["Fenerbahçe", "Chelsea", "Arsenal"] 
var kodlarJSON:String = "" 
var kodJSON:[String] = [] 

func jsonGetir(){ 

    let urls = NSURL(string: "http://gigayt.com/mackolik/deneme.php") 
    let sessions = NSURLSession.sharedSession().dataTaskWithURL(urls!){ 

     data, response, error -> Void in 

     if (error != nil){ print(error) } 

     do { 

      if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { 

       kodlarJSON = jsonResult["kodlar"] as! String //101,102,103 
       kodJSON = kodlarJSON.componentsSeparatedByString(",") 
       cekilecek_data.append(kodJSON[1]) //Here doesn't work! 

      } 

     } 

     catch { print(error) } 

    } 

    sessions.resume() 

} 

回答

1

刷新你的tableview你從服務器這種方式得到的數據之後:

dispatch_async(dispatch_get_main_queue()) { 
    self.tableView.reloadData() 
} 

而且你的最終代碼將是:

func jsonGetir(){ 

    let urls = NSURL(string: "http://gigayt.com/mackolik/deneme.php") 
    let sessions = NSURLSession.sharedSession().dataTaskWithURL(urls!){ 

     data, response, error -> Void in 

     if (error != nil){ print(error) } 

     do { 

      if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { 

       self.kodlarJSON = jsonResult["kodlar"] as! String //101,102,103 
       self.kodJSON = self.kodlarJSON.componentsSeparatedByString(",") 
       self.cekilecek_data.append(self.kodJSON[1]) //Here doesn't work! 

      } 

      dispatch_async(dispatch_get_main_queue()) { 
       self.tableView.reloadData() //Reload tableview here. 
      } 

     } 

     catch { print(error) } 

    } 

    sessions.resume() 

} 
+0

感謝感謝感謝!有用! –

+0

高興地幫助你.. :) –

0

隨着kodJSON = kodlarJson.componentsseparatedByString(",")要創建的唯一一個數組目的。然後使用cekilecke_data.append(kodJSON[1]),您試圖將數據追加到您僅設置一個對象的數組中的第二個對象。

do { 

     if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { 

      kodlarJSON = jsonResult["kodlar"] as! String 
      kodJSON = kodlarJSON.componentsSeparatedByString(",") 
       // this line sets kodJSON:[String] to ["kodlar"] 
      cekilecek_data.append(kodJSON[1]) //Here doesn't work! 
       // this tries to append cekilecek_data from index [1] or second slot of kodJSON which only has one entry 
     } 

    } 

如果你改變線路kodlarJSON = jsonResult["kod,lar"] as! String,它會工作,因爲kodJSON [1]就等於 「LAR」

相關問題