Populate UITableview with Array from Rest API in Swift - json

In my mainTableView Controller, I can print the API result in the console but I have no idea how I can set these to be visible in the cells of my tableview
import UIKit
//from: https://github.com/Ramotion/folding-cell
class MainTableViewController: UITableViewController {
let kCloseCellHeight: CGFloat = 179
let kOpenCellHeight: CGFloat = 488
let kRowsCount = 100
var cellHeights = [CGFloat]()
var restApi = RestApiManager()
var items: NSDictionary = [:]
override func viewDidLoad() {
super.viewDidLoad()
restApi.makeCall() { responseObject, error in
// use responseObject and error here
// self.json = JSON(responseObject!)
print("print the json data from api ")
self.items = NSDictionary(dictionary: responseObject!)
self.tableView.reloadData()
print(responseObject!.count)
// print(self.items)
let resultList = self.items["result"] as! [[String:
AnyObject]]
print(resultList[5])
}
createCellHeightsArray()
self.tableView.backgroundColor = UIColor(patternImage:
UIImage(named: "background")!)
}
// MARK: configure
func createCellHeightsArray() {
for _ in 0...kRowsCount {
cellHeights.append(kCloseCellHeight)
}
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
guard case let cell as DemoCell = cell else {
return
}
cell.backgroundColor = UIColor.clearColor()
if cellHeights[indexPath.row] == kCloseCellHeight {
cell.selectedAnimation(false, animated: false, completion:nil)
} else {
cell.selectedAnimation(true, animated: false, completion: nil)
}
cell.number = indexPath.row
}
// with as! the cell is set to the custom cell class: DemoCell
// afterwards all data can be loaded in this method
override func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCellWithIdentifier("FoldingCell",
forIndexPath: indexPath) as! DemoCell
//TODO: set all custom cell properties here (retrieve JSON and set in
cell), use indexPath.row as arraypointer
// let resultList = self.items["result"] as! [[String: AnyObject]]
// let itemForThisRow = resultList[indexPath.row]
// cell.schoolIntroText.text = itemForThisRow["name"] as! String
cell.schoolIntroText.text = "We from xx University..."
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return cellHeights[indexPath.row]
}
// MARK: Table vie delegate
override func tableView(tableView: UITableView,
didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath) as!
FoldingCell
if cell.isAnimating() {
return
}
var duration = 0.0
if cellHeights[indexPath.row] == kCloseCellHeight { // open cell
cellHeights[indexPath.row] = kOpenCellHeight
cell.selectedAnimation(true, animated: true, completion: nil)
duration = 0.5
} else {// close cell
cellHeights[indexPath.row] = kCloseCellHeight
cell.selectedAnimation(false, animated: true, completion:
nil)
duration = 0.8
}
UIView.animateWithDuration(duration, delay: 0, options:
.CurveEaseOut, animations: { () -> Void in
tableView.beginUpdates()
tableView.endUpdates()
}, completion: nil)
}
}
I get this result in JSON which is correct
{
result = (
{
city = Perth;
"cou_id" = AU;
environment = R;
image = "-";
name = "Phoenix English";
rating = 0;
"sco_id" = 2;
"sco_type" = LS;
},
{
city = "Perth ";
"cou_id" = AU;
environment = L;
image = "-";
name = "Milner college";
rating = 0;
"sco_id" = 3;
"sco_type" = LS;
},
what do I have to do to set these values and set them here?
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("FoldingCell", forIndexPath: indexPath) as! DemoCell
//TODO: set all custom cell properties here (retrieve JSON and set in cell), use indexPath.row as arraypointer
cell.schoolIntroText.text = "We from xx University..."
return cell
}
I somehow dont figure out how to construct an array from this JSON output and how to access these fields which seem to be nested in many dimensions,
as a noob, thx for any inputs.
Addition from class restApi:
// working method for calling api
func makeCall(completionHandler: (NSDictionary?, NSError?) -> ()) {
Alamofire.request(
.GET,
baseURL+schools+nonAcademicParameter,
headers: accessToken
)
.responseJSON { response in
switch response.result {
case .Success(let value):
completionHandler(value as? NSDictionary, nil)
case .Failure(let error):
completionHandler(nil, error)
}
}
}

At your TODO point:
let resultList = self.items["result"] as! [[String: AnyObject]]
let itemForThisRow = resultList[indexPath.row]
cell.cityLabel.text = itemForThisRow["city"] as! String
cell.nameLabel.text = itemForThisRow["name"] as! String
...
To make dealing with json easier in swift try SwiftyJSON.

I figured it out now. The size of the inner resultList array needs to be passed in numberOfRowsSelection. Then it loads the cell dynamically.
override func tableView(tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
print("size of self.resultlist.count: ")
print(self.resultList.count)
//size of the inner array with all the acutal values have to be 0
at the beginning. when the async call comes back with the whole
result, it will be updated. so it has to be set to the size of the
array
//http://www.unknownerror.org/opensource/Alamofire/Alamofire/q/stackoverflow/29728221/uitableview-got-rendered-before-data-from-api-returned-using-swiftyjson-and-alam
return self.resultList.count
}

Related

Issue adding sections to tableview from JSON data

I am trying to group my table view that is being populated from JSON data.
Here is an example of what it looks like:
[{"customer":"Customer1","serial":"34543453",
"rma":"P2384787","model":"M282","manufacturer":"Manufacturer1"},
{"customer":"Customer1","serial":"13213214",
"rma":"P2384787","model":"M384","manufacturer":" Manufacturer1"},
{"customer":"Customer2","serial":"1212121323",
"rma":"P3324787","model":"M384","manufacturer":" Manufacturer1"}]
I would like to group the table view based on the customer name.
So in my case, it should look like:
Customer1
34543453 - Manufacturer1 - M282
13213214 - Manufacturer1 - M384
Customer2
1212121323 - Manufacturer1 - M384
NOTE:
The reason there is a line separating the serial manufacturer and model is because of this separator in CustomerViewController.swift:
let titleStr = [item.serial, item.manufacturer, item.model].compactMap { $0 }.joined(separator: " - ")
PortfolioController.swift
import UIKit
class PortfolioController: UITableViewController {
var portfolios = [Portfolios]()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "Customer"
fetchJSON()
}
func fetchJSON(){
let urlString = "https://www.example.com/example/example.php"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, _, error) in
DispatchQueue.main.async {
if let error = error {
print("Failed to fetch data from url", error)
return
}
guard let data = data else { return }
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
self.portfolios = try decoder.decode([Portfolios].self, from: data)
self.tableView.reloadData()
} catch let jsonError {
print("Failed to decode json", jsonError)
}
}
}.resume()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return portfolios.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellId")
let customer = portfolios[indexPath.row]
//cell.textLabel?.text = customer.serial
let titleStr = [customer.serial, customer.manufacturer, customer.model].compactMap { $0 }.joined(separator: " - ")
print(titleStr)
// Get references to labels of cell
cell.textLabel!.text = titleStr
return cell
}
}
Portfolios.swift
import UIKit
struct Portfolios: Codable {
let customer, serial, rma, model: String
let manufacturer: String
}
1- Create an instance var
var portfoliosDic = [String:[Portfolios]]()
2- Assign it here
let res = try JSONDecoder().decode([Portfolios].self, from: data)
self.portfoliosDic = Dictionary(grouping: res, by: { $0.customer})
DispatchQueue.main.async {
self.tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return portfoliosDic.keys.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let keys = Array(portfoliosDic.keys)
let item = portfoliosDic[keys[section]]!
return item.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellId")
let keys = Array(portfoliosDic.keys)
let arr = portfoliosDic[keys[indexPath.section]]!
let customer = arr[indexPath.row]
//cell.textLabel?.text = customer.serial
let titleStr = [customer.serial, customer.manufacturer, customer.model].compactMap { $0 }.joined(separator: " - ")
print(titleStr)
// Get references to labels of cell
cell.textLabel!.text = titleStr
return cell
}

Trouble With SearchBar and Search Bar Controller Due to Depreciation of SearchDisplayController

I would like some help with the search bar functionality. I am stuck and not sure where to take it from here. I am trying to update the tableview when search text word is contained in a recipe title. I am not sure how to do this because of the depreciated searchDisplay controller. Help would be appreciated.
import UIKit
import SwiftyJSON
class Downloader {
class func downloadImageWithURL(_ url:String) -> UIImage! {
let data = try? Data(contentsOf: URL(string: url)!)
return UIImage(data: data!)
}
}
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchDisplayDelegate{
#IBOutlet weak var recipeTable: UITableView!
// search functionality Need help with my search functionality
var filteredRecipes = [Recipe]()
func filterContentForSearch(searchText:String) {
// need help here
self.filteredRecipes = self.recipes.filter({(title:Recipe) -> Bool in
return (title.title!.lowercased().range(of: searchText.lowercased()) != nil)
})
}
private func searchDisplayController(controller: UISearchController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
self.filterContentForSearch(searchText: searchString)
return true
}
//end search parameters
// tableview functionionalitys
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == searchDisplayController!.searchResultsTableView {
return filteredRecipes.count
}else{
return recipes.count
}
// recipeTable.reloadData()
}
// tableview functionalities
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! RecipeTableViewCell
if tableView == self.searchDisplayController!.searchResultsTableView{
//get images from download
DispatchQueue.main.async { () ->Void in
cell.imageLabel.image = Downloader.downloadImageWithURL(self.filteredRecipes[indexPath.row].imageUrl)
}
cell.recipeLabel.text = self.filteredRecipes[indexPath.row].title
recipeTable.reloadData()
}else{
//get image from download
DispatchQueue.main.async { () ->Void in
cell.imageLabel.image = Downloader.downloadImageWithURL(self.recipes[indexPath.row].imageUrl)
}
cell.recipeLabel.text = recipes[indexPath.row].title
}
//recipeTable.reloadData()
return cell
}
// structs for json
struct Root : Decodable {
let count : Int
let recipes : [Recipe]
}
struct Recipe : Decodable { // It's highly recommended to declare Recipe in singular form
let recipeId : String
let imageUrl, sourceUrl, f2fUrl : String
let title : String?
let publisher : String
let socialRank : Double
let page : Int?
let ingredients : [String]?
}
//recipes is array of Recipes
var recipes = [Recipe]() // array of recipes
//unfiltered recipes to put into search
fileprivate func getRecipes() {
let jsonURL = "https://www.food2fork.com/api/search?key=264045e3ff7b84ee346eb20e1642d9d9"
//.data(using: .utf8)!
guard let url = URL(string: jsonURL) else{return}
URLSession.shared.dataTask(with: url) {(data, response , err) in
if let response = response as? HTTPURLResponse, response.statusCode != 200 {
print(response.statusCode)
return
}
DispatchQueue.main.async {
if let err = err{
print("failed to get data from URL",err)
return
}
guard let data = data else{return}
//print(String(data: data, encoding: .utf8))
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder.decode(Root.self, from: data)
self.recipes = result.recipes
//print(result.recipes)
self.recipeTable.reloadData()
}catch let jsonERR {
print("Failed to decode",jsonERR)
}
}
}.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
//recipeTable.reloadData()
//search bar
//filteredRecipes = recipes
//call json object
getRecipes()
}
}
You could take this approach:
Add a Boolean variable to indicate whether searching or not
var searching: Bool = false
Use this for numberOfRowsInSection for the tableview
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching {
return filteredRecipes.count
} else {
return recipes.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! RecipeTableViewCell
var recipe: Recipe
if searching {
recipe = filteredRecipes[indexPath.row]
} else {
recipe = recipes[indexPath.row]
}
DispatchQueue.main.async { () ->Void in
cell.imageLabel.image = Downloader.downloadImageWithURL(recipe.imageUrl)
}
cell.recipeLabel.text = recipe.title
return cell
}
And add this for the searchBar (set searching for other funcs like searchBarCancelButtonClicked)
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
searching = false
filteredRecipes.removeAll()
view.endEditing(true)
} else {
searching = true
filteredRecipes = recipes.filter{$0.title.contains(searchBar.text!)}
}
tableView.reloadData()
}

Table empty when populating cells from json

I am trying to populate a table with json content. Everything seems to work fine except that the table is not showing any data. Actually, the code shown below should display the "title" information of each json data array into one cell. See line
cell.textLabel?.text = myNewsItems[indexPath.row].title
However, from what I can see in the console output, I can verify that the news array is parsed like expected (see Checkpoint: print(myNewsS)).
Any idea what I am missing?
Swift4
import UIKit
// structure from json file
struct News: Codable{
let type: String
let timestamp: String
let title: String
let message: String
}
class HomeVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
var myTableView = UITableView()
var myNewsItems: [News] = []
override func viewDidLoad() {
super.viewDidLoad()
let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height
myTableView = UITableView(frame: CGRect(x: 0, y: 150, width: displayWidth, height: displayHeight - barHeight))
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
myTableView.dataSource = self
myTableView.delegate = self
self.view.addSubview(myTableView)
// JSON
let url=URL(string:"https://api.myjson.com/bins/ywv0k")
let session = URLSession.shared
let task = session.dataTask(with: url!) { (data, response, error) in
// check status 200 OK etc.
guard let data = data else { return }
do {
let myNewsS = try
JSONDecoder().decode([News].self, from: data)
print(myNewsS)
DispatchQueue.main.async {
self.myTableView.reloadData()
}
} catch let jsonErr {
print("Error json:", jsonErr)
}
}
task.resume()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myNewsItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = myNewsItems[indexPath.row].title
return cell
}
}
Assign the array
myNewsItems = myNewsS
DispatchQueue.main.async {
self.myTableView.reloadData()
}

How to send data to table view with Alamofire And SwiftyJSON

I have a (large amount) of data that I want to send to Table View with alamofire and siftyJSON
web request :
let postEndPoint :String = "http://jsonplaceholder.typicode.com/posts/"
code Alamofire and SwiftyJSON:
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, postEndPoint).responseJSON { response in
// handle json
guard response.result.error == nil else{
print("error calling Get on /posts/1")
print(response.result.error)
return
}
if let value: AnyObject = response.result.value{
let post = JSON(value)
// for i in 0...post.count{
if let title = post["data"].arrayValue as? [JSON]{
self.datas = title
self.tableView.reloadData()
print("the title is :\(title)" )
}else{
print("eror parsing /post/1 ")
}
// }
}
}
}
code table view :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell")!
var dict = datas[indexPath.row]
cell.textLabel?.text = dict["userId"] as? String
cell.detailTextLabel?.text = dict["id"] as? String
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datas.count
}
}
web request :enter link description here
I am trying to post some json data to table view but when I send the data it returns nothing . why??
this is the code working for me. main thing is you have to reload the table at the end of api calling. and you are printing nuber as a string so you have to convert it to string
my code is here
import UIKit
class customcell: UITableViewCell {
#IBOutlet weak var lbl1: UILabel!
#IBOutlet weak var lbl2: UILabel!
}
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var tabledata: UITableView!
let postEndPoint :String = "http://jsonplaceholder.typicode.com/posts/"
var arr:NSMutableArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
web()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("customcell") as! customcell
let dict = arr[indexPath.row] as! NSDictionary
print(dict)
print(dict["userId"])
cell.lbl1?.text = String (dict["userId"]! )
cell.lbl2?.text = String (dict["id"]! )
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
func web()
{
request(.GET, postEndPoint, parameters: nil, encoding:
.JSON).responseJSON { (response:Response<AnyObject, NSError>) -> Void in
print(response.result.value)
if (response.result.value != nil)
{
self.arr = (response.result.value) as! NSMutableArray
}
self.tabledata.reloadData()
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (tableView == tabledata)
{
let cell = tableView.dequeueReusableCellWithIdentifier("customcell") as! customcell
let dict = arr[indexPath.row] as! NSDictionary
cell.lbl1?.text = String (dict["userId"]! )
cell.selectionStyle = .None
return cell
}
else if(tableView == tablefactoryoption)
{
let cell1:Facturyoptioncell = tableView.dequeueReusableCellWithIdentifier("Facturyoptioncell") as! Facturyoptioncell
let dict = arr[indexPath.row] as! NSDictionary
cell1.lbl2?.text = String (dict["Id"]! )
cell1.selectionStyle = .None
cell1.selectionStyle = .None
return cell1
}
else
{
let cell2:Technicalcell = tableView.dequeueReusableCellWithIdentifier("Technicalcell") as! Technicalcell
let dict = arr[indexPath.row] as! NSDictionary
cell2.lbl3?.text = String (dict["userId"]! )
return cell2
}
}
This is how you can use multiple tableview for display data.

append is not working

I have parsed a json string and i want to use it in a tableview. when i try to append the json string into an array the append method is not working. Here is the code that i have used. Can anyone help me with this?
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var userName = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// 1
let urlAsString = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php"
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
//2
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
print(error!.localizedDescription)
}
// 3
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
/*let err: NSError!
if (err != nil) {
print("JSON Error \(err.localizedDescription)")
}*/
// 4
//let fname: String! = jsonResult["firstname"] as! String
//let lname: String! = jsonResult["lastname"] as! String
//let usrname: String! = jsonResult["username"] as! String
dispatch_async(dispatch_get_main_queue(), {
if let users = jsonResult.objectForKey("Users") as? [[String:AnyObject]]
{
for user in users
{
print("First Name:")
print(user["firstname"]!)
print("Last Name:")
print(user["lastname"]!)
print("User Name:")
let nameUser = user["username"]! as! String
print(nameUser)
self.userName.append(nameUser)
print("***************")
}
}
//print(jsonResult["Users"]!)
//print(lname)
//print(usrname)
})
}
catch {
print("error");
}
})
jsonQuery.resume()
//self.userName.append("ganesh")
// 5
print(userName)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userName.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!
cell.textLabel?.text = userName[indexPath.row]
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
userName.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You are appending right in the array,Just call self.tableView.reloadData() to refresh table view at the end of dispatch to show the data in the tableView.
The append function works fine but you are filling the array in the background and never reloading the tableView when you have the data in the array
for user in users
{
if let nameUser = user["username"] as? String {
self.userName.append(nameUser)
}
}
self.tableView.reloadData()
Try this inside the if let users = jsonResult.objectForKey("Users") as? [[String:AnyObject]] block