3

I have managed to retrieve data from JSON using swiftJSON but I am facing problems when i try to populate tableview. I am new to iOS development, so please bear with me on this. I would appreciate if you could help or provide some ideas ?

Here's the code:

 override func viewDidLoad(){
 super.viewDidLoad()
 getContactListJSON()
 }

 func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
    let json = JSON(data: data)
    let contactsArray = json.arrayValue

    dispatch_async(dispatch_get_main_queue(), {
        for contacts in contactsArray
        {
            let id = contacts["id"].stringValue
            let name = contacts["name"].stringValue
            println( "id: \(id) name: \(name)" )
        }
    })
}
task.resume()
}
0

3 Answers 3

8

Here is your complete code for that:

import UIKit

class TableViewController: UITableViewController {

var tableName = [String]()
var tableID = [String]()
override func viewDidLoad() {
    super.viewDidLoad()
    getContactListJSON()

}

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

func getContactListJSON(){
    let urlString = "http://jsonplaceholder.typicode.com/users"
    let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
    let url = NSURL( string: urlEncodedString!)
    var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
        let json = JSON(data: data)
        let contactsArray = json.arrayValue

        dispatch_async(dispatch_get_main_queue(), {
            for contacts in contactsArray
            {
                let id = contacts["id"].stringValue
                let name = contacts["name"].stringValue
                println( "id: \(id) name: \(name)" )
                self.tableName.append(name)
                self.tableID.append(id)
            }
            dispatch_async(dispatch_get_main_queue(),{
                self.tableView.reloadData()
            })
        })
    }
    task.resume()
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

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


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

    // Configure the cell...
    cell.id.text = tableID[indexPath.row]
    cell.name.text = tableName[indexPath.row]
    return cell

    }
}

And HERE is working sample project for you with custom cell.

Sign up to request clarification or add additional context in comments.

Comments

0

First declare a local variable NSArray called contactsArray.

    override func viewDidLoad(){
                     super.viewDidLoad()

                     getContactListJSON()


                     }


    //Code for downloading data
     func getContactListJSON(){
                        let urlString = "http://jsonplaceholder.typicode.com/users"
                        let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
                        let url = NSURL( string: urlEncodedString!)
                        var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
                            let json = JSON(data: data)
                            self.contactsArray = json.arrayValue

                            dispatch_async(dispatch_get_main_queue(), {
                                [self.tableView reloadData]
                            })
                        }
                        task.resume()
                        }

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
                    var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
                    var contacts:NSDictionary = self.contactsArray[indexPath.row];
                    cell.textLabel?.text =   contacts["name"].stringValue
                    //.......
                    //.......

                    return cell
                }

3 Comments

Hi Thanks for your help, but I get an error on this line self.contactsArray = json.arrayValue "Cannot assign a value of type '[JSON]" to a value of type 'NSMutableArray'
another Error: "Cannot find an initializer for type 'NSMutableArray' that accepts an argument list of type '(array: [JSON])"
nope, didn't work. Error again. I also tried self.contactsArray = NSArray(array: json.arrayValue) didn't work either.
0

Here is a piece of code.

var dataArray = [String]()

override func viewDidLoad(){
 super.viewDidLoad()
 getContactListJSON()
 }

 func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
    let json = JSON(data: data)
    let contactsArray = json.arrayValue

    dispatch_async(dispatch_get_main_queue(), {
        for contacts in contactsArray
        {
            let id = contacts["id"].stringValue
            let name = contacts["name"].stringValue
            println( "id: \(id) name: \(name)" )
            self.dataArray.append(name)
        }
        self.tableView.reloadData()
    })
}
task.resume()
}

Here i am taking name. If you want to display id as well, then create a model class for it.

3 Comments

Appreciate your help but other examples were more clear. Thanks!
why dispatch_async is called twice ? I have Index out of range because of it
You are right, there is no need of two dipatch_async. Sorry my mistake, corrected now.

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.