【问题标题】:Populate JSON data from REST API to table view in swift not working快速将 REST API 中的 JSON 数据填充到表格视图中不起作用
【发布时间】:2016-02-25 10:44:05
【问题描述】:

我在日志窗口中获得了响应数据,但我无法动态填充 tableView。我尝试了很多方法,但都不起作用

// send request to URL
    let urlPath:String = "http://api.androidhive.info/contacts/"
    var url:NSURL = NSURL(string: urlPath)!
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
    request1.HTTPMethod = "POST"
    var stringPost = "msg=123"  ///key and value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
    request1.timeoutInterval = 60
    request1.HTTPBody = data
    request1.HTTPShouldHandleCookies = false

    let queue:NSOperationQueue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler: {(response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in

        //print  object response
        println("response =  \(response)")
        //print response body
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("response data = \(responseString)")

数据来自 url。我可以看到它。

 // Extract JSON

           var err: NSError?
        let json : NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary

        if let items = json["contacts"] as? [[String:AnyObject]]
        {
            for item in items {

                // construct your model objects here
                self.contactList.append(Person(dictionary:item))
            }

            // dispatch_async(dispatch_get_main_queue()) {

            // self.tableView.reloadData()
        }

上面的代码行没有附加数据(不工作)。

表格视图代码

  //how many sections
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

    //how many rows
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return contactList.count
    //return cellCount
}
//contents
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
   // var cell = UITableViewCell()
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

   // cell.textLabel?.text = "aaa"
    let person = contactList[indexPath.row]
    cell.textLabel?.text = person.name

    return cell
}

请告诉我问题出在哪里。

【问题讨论】:

标签: ios iphone json swift


【解决方案1】:

这是一个创建自定义类的好例子

class Person { // can be also a struct

  let id : String
  let name : String
  let email : String
  let address : String
  let gender : String
  let phone : String

  init(dictionary : [String : AnyObject]) {
    id = dictionary["id"] as? String ?? ""
    name = dictionary["name"] as? String ?? ""
    email = dictionary["email"] as? String ?? ""
    address = dictionary["address"] as? String ?? ""
    gender = dictionary["gender"] as? String ?? ""
    phone = dictionary["id"] as? String ?? ""
  }
}

然后创建contactList

var contactList = [Person]()

并用

填充列表
if let items = json["contacts"] as? [[String:AnyObject]]
 {
    for item in items {
      // construct your model objects here
      self.contactList.append(Person(dictionary:item))
    }
    dispatch_async(dispatch_get_main_queue()) {
       self.tableView.reloadData()
    }
 }

并在每个单元格中显示名称

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
   // var cell = UITableViewCell()
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

    let person = contactList[indexPath.row]
    cell.textLabel?.text = person.name
    return cell
}    

如果包含人员数据的字典的所有值都是String 类型,您可以更改以下行以更加具体

Person

init(dictionary : [String : String]) {
    id = dictionary["id"] ?? ""
    ...
    phone = dictionary["id"] ?? ""
  }

在视图控制器中

if let items = json["contacts"] as? [[String:String]]

【讨论】:

  • 我自己会使用结构而不是类。
  • 是的,两者都可以。
  • 我应该在哪里创建自定义类。在另一个 swift 文件或其他地方。
  • 推荐的地方是单独的 Swift 文件
  • 我添加了另一个名为 person 的 swift 文件,并在其中创建了 person 类。 @vadian 。方法对不对?
【解决方案2】:

创建 NSObject 类

   public class Global: NSObject
   {
      let name : String!
        .
        .
    } 

项目中的项目内

var object: ObjectClass = ObjectClass()
object.id = item["id"]!
  .
  .
  self.contactList.append(object)

在 cellForRowAtIndexPath 中

   var object: ObjectClass = self.contactList [indexPath.row] as! ObjectClass;

   ///get the values as 
   cell.label.text = object.name;

【讨论】:

    【解决方案3】:

    改为创建模型。您可以为联系人创建类。

        class Contact {
            var id : String?
            var name : String?
        }
    

    创建一个示例响应。

        // Contact1
        let cont1 : NSMutableDictionary = NSMutableDictionary.init(object: "7", forKey: "id");
        cont1.setValue("vignesh", forKey: "name");
        // Contact2
        let cont2 : NSMutableDictionary = NSMutableDictionary.init(object: "8", forKey: "id");
        cont2.setValue("karthi", forKey: "name");
    
        let contactArray :NSArray = NSArray.init(array: [cont1,cont2]);
    
        // Response Dictionary
        let responseDic : NSMutableDictionary = NSMutableDictionary.init(object: contactArray, forKey: "contacts");
    

    解析响应值。

        // Create Contact list Array.
        var contactList : Array<Contact> = []
    
        if let items = responseDic["contacts"] as? NSArray
        {
            for item in items {
                // construct your model objects here
                let id: NSString = item["id"] as! NSString
                let name: NSString = item["name"] as! NSString
    
                let contUser : Contact = Contact.init();
                contUser.id = id as String;
                contUser.name = name as String;
                contactList.append(contUser)
            }
        }
    
    1. 列表项

    【讨论】:

      【解决方案4】:

      类 ViewController: UIViewController , UITableViewDataSource , UITableViewDelegate {

      @IBOutlet weak var tableViewCountry: UITableView!
      var names: [String] = []
      var contacts: [String] = []
      var gender: [String] = []
      var mob:[String] = []
      
      override func viewDidLoad() {
          super.viewDidLoad()
          tableViewCountry.dataSource = self
          tableViewCountry.delegate = self
      
          self.tableViewCountry.register(UINib(nibName: "ContactTableViewCell", bundle: nil), forCellReuseIdentifier: "ContactTableViewCell")
      
      
          let url=URL(string:"http://api.androidhive.info/contacts/")
          do {
              let allContactsData = try Data(contentsOf: url!)
              let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
              if let arrJSON = allContacts["contacts"] {
                  for index in 0...arrJSON.count-1 {
      
                      let aObject = arrJSON[index] as! [String : AnyObject]
      
                      names.append(aObject["name"] as! String)
                      contacts.append(aObject["email"] as! String)
                      gender.append(aObject["gender"] as! String)
      
                      let phone = aObject["phone"]
                      mob.append(phone?["mobile"] as! String)
      
                  }
              }
              print(allContacts)
              print(names)
              print(contacts)
      
              self.tableViewCountry.reloadData()
          }
          catch {
              print("error")
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-06-01
        • 2011-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多