2016-01-20 3 views
1

У меня есть (большой объем) данных, что я хочу, чтобы отправить Table View с alamofire и siftyJSONКак отправить данные в виде таблицы с Alamofire И SwiftyJSON

веб-запрос:

let postEndPoint :String = "http://jsonplaceholder.typicode.com/posts/" 

код Alamofire и SwiftyJSON:

override func viewDidLoad() { 
    super.viewDidLoad() 

    Alamofire.request(.GET, postEndPoint).responseJSON { response in 
     // handle json 
     guard response.result.error == nil else{ 
      print("error calling Get on /posts/1") 
      print(response.result.error) 
      return 

     } 


     if let value: AnyObject = response.result.value{ 

      let post = JSON(value) 
      // for i in 0...post.count{ 
      if let title = post["data"].arrayValue as? [JSON]{ 
        self.datas = title 
       self.tableView.reloadData() 
       print("the title is :\(title)") 
      }else{ 

       print("eror parsing /post/1 ") 

      } 

      // }    

     } 
     } 

} 

код табличное:

func tableView(tableView: UITableView, cellForRowAtIndexPath   indexPath: NSIndexPath) -> UITableViewCell { 
    let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell")! 
    var dict = datas[indexPath.row] 
    cell.textLabel?.text = dict["userId"] as? String 
    cell.detailTextLabel?.text = dict["id"] as? String 
    return cell 
} 

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

}

веб-запрос: enter link description here

Я пытаюсь опубликовать некоторые данные JSON в виде таблицы, но когда я отправить данные, которые он не возвращает ничего. Зачем??

ответ

5

Это код, который работает для меня. главное, вам нужно перезагрузить таблицу в конце вызова api. и вы печатаете Nuber в виде строки, так что вы должны преобразовать его в строку

enter image description here

мой код здесь

import UIKit 

класс customcell: UITableViewCell {

@IBOutlet weak var lbl1: UILabel! 

@IBOutlet weak var lbl2: UILabel! 

}

класс ViewController: UIViewController, UITable ViewDataSource, UITableViewDelegate {

@IBOutlet weak var tabledata: UITableView! 
let postEndPoint :String = "http://jsonplaceholder.typicode.com/posts/" 
var arr:NSMutableArray = NSMutableArray() 
override func viewDidLoad() { 
    super.viewDidLoad() 
    web() 
    // Do any additional setup after loading the view, typically from a nib. 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("customcell") as! customcell 

    let dict = arr[indexPath.row] as! NSDictionary 
    print(dict) 

    print(dict["userId"]) 
    cell.lbl1?.text = String (dict["userId"]!) 
    cell.lbl2?.text = String (dict["id"]!) 

    return cell 

} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return arr.count 
} 
func web() 
{ 
    request(.GET, postEndPoint, parameters: nil, encoding: 
     .JSON).responseJSON { (response:Response<AnyObject, NSError>) -> Void in 

      print(response.result.value) 
      if (response.result.value != nil) 
      { 
       self.arr = (response.result.value) as! NSMutableArray 

      } 

      self.tabledata.reloadData() 
    } 
} 

}

+0

tank you @Raj :) один вопрос, как я могу передать эти данные в виде нескольких таблиц? –

+0

спасибо @Raj :). –

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


    if (tableView == tabledata) 
    { 
    let cell = tableView.dequeueReusableCellWithIdentifier("customcell") as! customcell 

     let dict = arr[indexPath.row] as! NSDictionary 
     cell.lbl1?.text = String (dict["userId"]!) 
     cell.selectionStyle = .None 
     return cell 
    } 

    else if(tableView == tablefactoryoption) 
    { 
     let cell1:Facturyoptioncell = tableView.dequeueReusableCellWithIdentifier("Facturyoptioncell") as! Facturyoptioncell 


     let dict = arr[indexPath.row] as! NSDictionary 
     cell1.lbl2?.text = String (dict["Id"]!) 
     cell1.selectionStyle = .None 


    cell1.selectionStyle = .None 

     return cell1 

    } 

    else 
    { 
     let cell2:Technicalcell = tableView.dequeueReusableCellWithIdentifier("Technicalcell") as! Technicalcell 

     let dict = arr[indexPath.row] as! NSDictionary 
     cell2.lbl3?.text = String (dict["userId"]!) 
     return cell2 

    } 

} 

Это, как вы можете использовать несколько TableView для отображения данных.

+0

танк вас. но я делаю это с сего. –

+0

Как я могу использовать этот json Я создаю несколько вложенных таблиц? –

+0

Я не получаю ваш вопрос, можете ли вы объяснить немного больше? –

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