0

I have got the response data in the log window but I am not able to populate on the tableView dynamically. I have tried many methods but not working

// 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)")

The data is coming from the url. I can see it.

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

The above code line is not appending data (not working).

Table view code

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

Please tell me where the problem is.

1

4 Answers 4

1

That's a good example to create a custom class

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 ?? ""
  }
}

Then create contactList as

var contactList = [Person]()

and populate the list with

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()
    }
 }

and display the name in each cell

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
}    

If all values of the dictionary containing the person data are of type String you can change the following lines to be still more specific

in Person

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

in the view controller

if let items = json["contacts"] as? [[String:String]]
Sign up to request clarification or add additional context in comments.

8 Comments

I'd use a struct instead of a class, myself.
Yes, it could be both.
where should i create the custom class. in another swift file or some other place.
The recommended place is a separate Swift file
i have added another swift file named person and in that created the person class. @vadian . its the correct way or not?
|
0

Create NSObject class

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

Within for item in items

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

In cellForRowAtIndexPath

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

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

Comments

0

Instead create model. you can create Class for Contact.

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

Create a Sample responses.

    // 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");

Parse Response value.

    // 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. List item

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.