JSON TableView Swift Error - ios

I'm trying to populate a tableview with this JSON URL. I validated the URL, and it works fine. My code is at fault. I have a 'Repository.swift' file with a class inside. Here's my code: I can't resolve the issue.
var repositories = [Repository]()
override func viewDidLoad() {
super.viewDidLoad()
let reposURL = NSURL(string: "https://www.kimonolabs.com/api/7flcy3qm?apikey=gNq3hB1j0NtBdAvXJLEFx8JaqtDG8y6Y")!
if let JSONData = NSData(contentsOfURL: reposURL) {
if let json = NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
if let reposArray = json["items"] as? [NSDictionary] {
for item in reposArray {
repositories.append(Repository(json: item))
}
}
}
}
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.repositories.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = repositories[indexPath.row].Event
cell.detailTextLabel?.text = repositories[indexPath.row].Hasta
return cell
}

You need to add try catch
I fixed your code
override func viewDidLoad() {
super.viewDidLoad()
let reposURL = NSURL(string: "https://www.kimonolabs.com/api/7flcy3qm?apikey=gNq3hB1j0NtBdAvXJLEFx8JaqtDG8y6Y")!
if let JSONData = NSData(contentsOfURL: reposURL) {
do{
let json = try NSJSONSerialization.JSONObjectWithData(JSONData, options: .MutableContainers)
if let reposArray = json["items"] as? [NSDictionary] {
for item in reposArray {
// repositories.append(Repository(json: item))
}
}
}catch {
//do whatever
}
}
}
Kindly try it.

Related

Value of type 'UITableViewCell' has no member 'name' in multiple TableView

I tried to make ViewController with two TableView but meet the problem.
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableTN: UITableView!
#IBOutlet weak var tableMainNews: UITableView!
var topnews: [TopNews]? = []
var mainnews: [Mainnewsfeed]? = []
override func viewDidLoad() {
super.viewDidLoad()
TopNewsJSON()
MainNewsJSON()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell?
if tableView == self.tableTN {
cell = tableView.dequeueReusableCell(withIdentifier: "topnewsCell", for:indexPath) as! TopNewsCell
cell!.imgTN!.downloadImage(from: (self.topnews?[indexPath.item].image!)!)
cell!.titleTN!.text = self.topnews?[indexPath.item].headline
}
if tableView == self.tableMainNews {
cell = tableView.dequeueReusableCell(withIdentifier: "mainnewsCell", for:indexPath) as! MainNewsCell
cell!.mainnews_title!.text = self.mainnews?[indexPath.item].headline
}
return cell!
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count:Int?
if tableView == self.tableTN {
count = self.topnews!.count
}
if tableView == self.tableMainNews {
count = self.mainnews!.count
}
return count!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//print(indexPath)
}
func TopNewsJSON () {
let urlRequest = URLRequest(url: URL(string: "https://sportarena.com/wp-api/topnews2018/top/")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error as Any)
return
}
self.topnews = [TopNews]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
//print(json)
let TN = TopNews()
let jarray = json["top-news"] as! NSArray
let jarray1 = jarray[0] as? [String: AnyObject]
if let ID = jarray1!["ID"] as? String,
let title = jarray1!["title"] as? String,
let img = jarray1!["img"] as? String {
TN.headline = title
TN.image = img
TN.id = ID
}
self.topnews?.append(TN)
DispatchQueue.main.async {
self.tableTN.reloadData()
}
} catch let error {
print(error)
}
}
task.resume()
}
func MainNewsJSON () {
let urlRequest = URLRequest(url: URL(string: "anyurl")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error as Any)
return
}
//self.mainnews = [MainNews]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
let jarray = json["general-news"] as! NSArray
let jarray1 = jarray[0]
for jarray1 in jarray1 as! [[String: Any]] {
let MNF = Mainnewsfeed()
if let ID = jarray1["id"],
let title = jarray1["title"],
let time = jarray1["datetime"] {
MNF.headline = title as? String
MNF.id = ID as? String
MNF.time = time as? String
}
self.mainnews?.append(MNF)
DispatchQueue.main.async {
self.tableMainNews.reloadData()
}
}
} catch let error {
print(error)
}
}
task.resume()
}
}
}
After three lines as cell!.titleTN!.text = self.topnews?[indexPath.item].headline and others display error: "Value of type 'UITableViewCell' has no member 'titleTN'" (or also 'imgTN' and 'mainnews_title')
Where the error? What I need to change in my code?
Please help me.
You can try
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.tableTN {
let cell = tableView.dequeueReusableCell(withIdentifier: "topnewsCell", for:indexPath) as! TopNewsCell
cell.imgTN!.downloadImage(from: (self.topnews?[indexPath.item].image!)!)
cell.titleTN!.text = self.topnews?[indexPath.item].headline
return cell
}
else
{
let cell = tableView.dequeueReusableCell(withIdentifier: "mainnewsCell", for:indexPath) as! MainNewsCell
cell.mainnews_title!.text = self.mainnews?[indexPath.item].headline
return cell
}
}

No data coming in from parsing JSON with Alamofire Swift 3 and Xcode 8 beta

I am trying to get data from an url in Swift 3 with Alamofire. There is no data coming through on the cell. I know I am messing something up somewhere but I am fairly new to swift 3 and cant see the issue, the code is below:
JSON Structure.
{
posts: 
 [

 {
id: “000000”,
url: "/content/interview",
date: "2016-11-03 09:01:41",
modified: "2016-11-03 09:03:47",
title: "An interview",
summary: 
 {
value: "<p>Lorem ipsum is simply dummy text</p> ",
format: "filtered_html"
}
]
}
Swift:
import UIKit
import Alamofire
class TableViewController: UITableViewController {
var titles = [String]()
var mainURL = "https://www.testapi.com"
typealias JSONstandard = [String : AnyObject]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
callAlamo(url: mainURL)
}
func callAlamo(url : String){
Alamofire.request(url).responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
})
}
func parseData(JSONData : Data) {
do {
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONstandard
print(readableJSON)
if let post = readableJSON["posts"] as? JSONstandard {
if let posts = post["posts"] {
for i in 0..<posts.count {
let post = posts[i] as! JSONstandard
let title = post["title"] as! String
titles.append(title)
self.tableView.reloadData()
}
}
}
}
catch {
print(error)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = titles[indexPath.row]
return cell!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The above bring no data into the "cell". Any help would be appreciated.
First of all a JSON dictionary in Swift 3 is [String:Any]
typealias JSONstandard = [String : Any]
The author of the tutorial should name it JSONdictionary to make it clearer.
The value for posts is an array, JSON collection objects are very easy to identify:
[] is array
{} is dictionary
...
if let posts = readableJSON["posts"] as? [JSONstandard] {
for post in posts { // don't use ugly C-style loops
let title = post["title"] as! String
titles.append(title)
}
self.tableView.reloadData() // reload the table view after the loop
}
...
PS : In Swift (1-3) passing .mutableContainers is pretty useless.
Add UITableViewDataSource methode:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
Do not reloadData()too often:
func parseData(JSONData : Data) {
do {
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONstandard
print(readableJSON)
if let post = readableJSON["posts"] as? JSONstandard {
if let posts = post["posts"] {
for i in 0..<posts.count {
let post = posts[i] as! JSONstandard
let title = post["title"] as! String
titles.append(title)
}
self.tableView.reloadData() // moved out of loop
}
}
}
catch {
print(error)
}
}
If the problem persists:
Log: titles.count
You problem is here may be
if let posts = post["posts"] {
---
}
in previous line you get posts by readableJSON["posts"]. Post has no node named "posts".
try this code:
if let allPost = readableJSON["posts"] {
var posts = allPost as! NSArray
for post in posts {
let title = post["title"] as! String
titles.append(title)
self.tableView.reloadData()
}
}

Swift uitableview json delete row

I have a tableview with JSON data where I can delete mysql data by JSON with Delete button action throw a method. But does not find out a way to delete from cell.
Here is screen shot and code
//Send user data to server side
#IBAction func deleteData(sender: AnyObject) {
let adduser = lblName.text
let id = store.storeId
//Send user data to server side
let myUrl = NSURL(string: "http://localhost/crud/delete.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "id=\(id)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{
data, response, error in
if error != nil {
print("error=\(error)")
return
}
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON=json{
var resultValue = parseJSON["status"] as! String
print("result: \(resultValue)")
var isUserRegistered:Bool = false;
if(resultValue=="Success") {isUserRegistered = true; }
var messageToDisplay:String = parseJSON["status"] as! String
if(!isUserRegistered)
{
messageToDisplay = parseJSON["message"] as! String;
}
//self.store.storeName = self.lblName.text!
//store?.sName = txtName.text!
self.store.storeName = self.lblName.text!
dispatch_async(dispatch_get_main_queue(), {
// Display alert message with confirmation.
var myAlert = UIAlertController(title:"Alert", message:messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default) {action in
self.dismissViewControllerAnimated(true, completion:nil);
}
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion:nil);
});
}
}catch{print(error)}
}
task.resume()
}
TableViewController
class TableViewController: UITableViewController {
var storeList = [Store]()
//var storeList:Store?
override func viewDidLoad() {
super.viewDidLoad()
/*
if let s = storeList
{
txtName.text = s.storeName
}
*/
// Uncomment the following line to preserve selection between presentations
//self.clearsSelectionOnViewWillAppear = true
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.loadRecords()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData() // to reload selected cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return storeList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! StoreTVC
let s = storeList[indexPath.row] as Store
cell.lblName.text = s.storeName
//cell.lblID.text = s.storeId
return cell
}
// for swipe delete
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
storeList.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
/*
if segue.identifier == "details"
{
//if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)
if let indexPath = tableView.indexPathForSelectedRow
{
let s = storeList[indexPath.row] as Store
let dvc = segue.destinationViewController as! ViewDetails
dvc.store = s
}
}
*/
if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)
{
let s = storeList[indexPath.row] as Store
let dvc = segue.destinationViewController as! ViewDetails
dvc.store = s
}
}
func loadRecords()
{
//The address of the web service
let urlString = "http://localhost/crud/read_for_table_view.php"
// 1 - Create the session by getting the configuration and then crrating the session
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil)
//2 - Create the URL Object
if let url = NSURL(string: urlString)
{
//3 - Create the request object
let request = NSURLRequest(URL: url)
//4 - execute the request
let taskData = session.dataTaskWithRequest(request, completionHandler: {
(data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in
//5 - Do something with the Data back
if(data != nil)
{
//we got some data back
print("\(data)")
/*
var parseError:NSError?
let parsedStores = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parseError) as! NSDictionary
*/
do {
if let parsedStores = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("Json Data \n \(parsedStores)")
if let stores:AnyObject = parsedStores["result"]
{
self.parseJSON(stores)
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
}else
{
//we got an error
print("Error getting stores :\(error!.localizedDescription)")
}
})
taskData.resume()
}
}
func parseJSON(jsonData:AnyObject)
{
if let storeData = jsonData as? [[NSObject:AnyObject]]
{
var store:Store
//we loop through all the recors and everytime we create
// an object of kind store and then add to the store list
for s in storeData
{
store = Store()
// this part is getting the values
if let sId:AnyObject = s["id"]
{
if let storeID = sId as? String
{
print("Store id = \(storeID)")
store.storeId = storeID
}
}
if let sn:AnyObject = s["name"]
{
if let storeName = sn as? String
{
store.storeName = storeName
}
}
storeList += [store]
}
NSOperationQueue.mainQueue().addOperationWithBlock()
{
self.tableView.reloadData()
}
}
}
}
Can someone please help?
After deleting data from mysql,
1) you will have to delete cell from tableview as follow.
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
in first argument you will have to pass array of indexpaths which cells you want to delete.
2) Or else you can again fetch data from Database & reload table..
//code for fetching data from database
self.tableView.reloadData()
There is basically 2 things ....
1st is just put your self.loadRecords() in viewWillAppear method
and 2nd one remove all objects from array before parse it once again like
func parseJSON(jsonData:AnyObject)
{
storeList.removeAll()
//....
}

not showing data in table view swift

i have one table view with two labels. I need to display the data which are coming from json. But now its not showing any data in table view:
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate
{
let yourJsonFormat: String = "JSONFile" // set text JSONFile : json data from file
// set text JSONUrl : json data from web url
var arrDict :NSMutableArray=[]
#IBOutlet weak var tvJSON: UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
if yourJsonFormat == "JSONFile" {
jsonParsingFromFile()
} else {
jsonParsingFromURL()
}
}
func jsonParsingFromURL () {
let url = NSURL(string: "url")
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
}
}
func jsonParsingFromFile()
{
let path: NSString = NSBundle.mainBundle().pathForResource("days", ofType: "json")!
let data : NSData = try! NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMapped)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return arrDict.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell : TableViewCell! = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell
let strTitle : NSString=arrDict[indexPath.row] .valueForKey("name") as! NSString
let strDescription : NSString=arrDict[indexPath.row] .valueForKey("rating") as! NSString
cell.lblTitle.text=strTitle as String
cell.lbDetails.text=strDescription as String
return cell as TableViewCell
}
}
Any thing i missed,please help me out.
I am not able to see any data in my table view...
your code is partially correct, I followed your question
Step-1
Right click on the info.plist file, select open as, Source code. Add the lines of code that allow the http connection to this server.
do like
Step-2
For Server request
sendAsynchronousRequest is deprecated in this place use
func jsonParsingFromURL () {
let url = NSURL(string: "url")
let session = NSURLSession.sharedSession()
let request = NSURLRequest(URL: url!)
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
print("done, error: \(error)")
let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
arrDict.addObject((dict.valueForKey("xxxx")
tvJSON .reloadData()
}
dataTask.resume()
}
For local Request
func jsonParsingFromFile()
{
let path: NSString = NSBundle.mainBundle().pathForResource("days", ofType: "json")!
let data : NSData = try! NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMapped)
let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
arrDict.addObject((dict.valueForKey("xxxx")
tvJSON .reloadData()
}
Update and Edit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet var showtable: UITableView!
var arrDict :NSMutableArray=[]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.jsonParsingFromURL()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func jsonParsingFromURL () {
let url = NSURL(string: "http://kirisoft.limitscale.com/GetVendor.php?category_id=1")
let session = NSURLSession.sharedSession()
let request = NSURLRequest(URL: url!)
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
print("done, error: \(error)")
if error == nil
{
self.arrDict=(try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSMutableArray
print(self.arrDict)
if (self.arrDict.count>0)
{
self.showtable.reloadData()
}
// arrDict.addObject((dict.valueForKey("xxxx")
}
}
dataTask.resume()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return arrDict.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let CellIdentifier: String = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as UITableViewCell!
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: CellIdentifier)
}
cell?.textLabel!.text=arrDict[indexPath.row] .valueForKey("name") as? String
cell?.detailTextLabel!.text=arrDict[indexPath.row] .valueForKey("rating") as? String
return cell!
}
}
you can get the output like
For sample Project

how to populate data in UITableView ? swift

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

Resources