2015-08-07 5 views
0

У меня есть данные JSON, которые я хочу получить в UITable. Данные динамические, поэтому таблица должна обновлять каждую загрузку времени. Может ли кто-нибудь помочь?iOS Swift получает данные JSON в таблицуView

{ 
data =  (
       { 
      id = 102076330; 
      name = "Vicky Arora"; 
     } 
    ) 
} 
+0

Вы уверены, что это правильный формат JSON? –

+0

@ Dato'MohammadNurdin Это фактические данные. { данные = ( { ID = 1020763302139; имя = "Vicky Arora"; } ); paging = { next = "https://graph.facebook.com/v2.4/XXXXXX"; }; summary = { "total_count" = 13; }; } –

ответ

1

попробовать это ....

Когда вы получите ответ, получить весь массив словаря

if let arr = response["data"] as? [[String:String]] { 
     YourArray = arr 
     // Define YourArray globally 
} 

Затем в Tableview клетки, cellForRowAtIndexPath метод

if let name = YourArray[indexpath.row]["name"] as? String{ 
     label.text = name 
} 
//Same You can done with id 

И не забудьте установить количество строк

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    // #warning Incomplete method implementation. 
    // Return the number of rows in the section. 
    return YourArray.count 
} 
+0

Использование неразрешенного идентификатора "responseObject"? Вы знаете, что это? –

+0

просто покажите мне, как вы получили ответ ... и я скажу вам, что делать? –

+0

Я правильно понял YourArray. [[id: 102076330, имя: Vicky Arora]], но когда я использую это в UITableView cellForRow, я получаю «фатальную ошибку: индекс массива вне диапазона». если пусть name = YourArray [indexPath.row] ["name"] { cell.detailTextLabel! .text = name }. Я пробовал, если пусть name = YourArray [indexPath.row] - он все еще сбой в этой строке с индексом Array вне диапазона. –

0

Если вы используете Core Data, я бы предложил использовать NSFetchedRequest.

Каждый раз, когда вы получаете данные с сервера, сохраните его на основе данных Core и автоматически обновите представление таблицы.

Вот учебник от Ray Wenderlich

1

Попробуйте это. Но этот образец я использую Alamofire и SwitfyJSON. Импортируйте его с помощью CocoaPod.

import UIKit 
import Alamofire 

class TableViewController: UITableViewController{ 

    var users: [JSON] = [] 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     Alamofire.request(.GET, "http://xxxxx/users.json").responseJSON { (request, response, json, error) in 
      if json != nil { 
       var jsonObj = JSON(json!) 
       if let data = jsonObj["data"].arrayValue as [JSON]?{ 
        self.users = data 
        self.tableView.reloadData() 
       } 
      } 
     } 
    } 

    // MARK: - Table view data source 

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     // #warning Potentially incomplete method implementation. 
     // Return the number of sections. 
     return 1 
    } 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     // #warning Incomplete method implementation. 
     // Return the number of rows in the section. 
     return users.count 
    } 

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCellWithIdentifier("UserCell", forIndexPath: indexPath) as! UITableViewCell 
     let user = users[indexPath.row] 
     if let idLabel = cell.viewWithTag(100) as? UILabel { 
      if let id = user["id"].string{ 
       idLabel.text = id 
      } 
     } 

     if let nameLabel = cell.viewWithTag(101) as? UILabel { 
      if let name = user["name"].string{ 
       nameLabel.text = name 
      } 
     } 

     return cell 
    } 

} 
Смежные вопросы