将REST API中的JSON数据填充到swift中的表视图不起作用

时间:2016-02-25 10:44:05

标签: ios iphone json swift

我在日志窗口中收到了响应数据,但我无法动态填充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)")

数据来自网址。我可以看到它。

 // 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
}

请告诉我问题所在。

4 个答案:

答案 0 :(得分: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]]

答案 1 :(得分:0)

创建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;

答案 2 :(得分:0)

而是创建模型。您可以创建联系人类。

    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. 列表项

答案 3 :(得分:0)

类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")
    }
}