Error setting UILabel text in custom UITableViewCell - ios

I am quite new to Swift programming, but I am having trouble setting UILabel text in my UITableView class for individual UITableViewCell instances.
I have created a custom subclass of UITableViewCell called PizzaTableViewCell and a custom UITableView class called PizzaListTableViewController. I am trying to populate the UITableView instance with data from an array, which is being populated from an API call to my node.js server.
I have included my UITableView subclass, custom UITablveViewCell class, the struct for the data, and a link to a screenshot of the Simulator loading what I have done. Any help is greatly appreciated!
I have verified that the data is being put in the array with no issues, as I can print the contents after the call to fetchInventory method. I have been able to set a single textLabel with
cell.textLabel?.text = pizzas[indexPath.row].name
along with an image in the array with:
cell.imageView?.image = pizzas[indexPath.row].image
but I have 2 more labels that I need in each cell which I cannot set. I have checked my IBOutlets and Storyboard identifiers, and they match the code.
class PizzaListTableViewController: UITableViewController {
var pizzas: [Pizza] = []
override func viewDidLoad() {
super.viewDidLoad()
//title you will see on the app screen at the top of the table view
navigationItem.title = "Drink Selection"
tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza")
//tableView.estimatedRowHeight = 134
//tableView.rowHeight = UITableViewAutomaticDimension
fetchInventory { pizzas in
guard pizzas != nil else { return }
self.pizzas = pizzas!
print(self.pizzas)
//self.tableView.reloadData()
//print(self.pizzas)
DispatchQueue.main.async { [weak self] in
self?.tableView.reloadData()
}
}
} //end of viewDidLoad
private func fetchInventory(completion: #escaping ([Pizza]?) -> Void) {
Alamofire.request("http://127.0.0.1:4000/inventory", method: .get)
.validate()
.responseJSON { response in
guard response.result.isSuccess else { return completion(nil) }
guard let rawInventory = response.result.value as? [[String: Any]?] else { return completion(nil) }
let inventory = rawInventory.compactMap { pizzaDict -> Pizza? in
var data = pizzaDict!
data["image"] = UIImage(named: pizzaDict!["image"] as! String)
//print(data)
//print("CHECK")
print("Printing each item: ", Pizza(data: data))
//printing all inventory successful
return Pizza(data: data)
}
completion(inventory)
}
}
#IBAction func ordersButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "orders", sender: nil)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//PRINTING ROWS 0 TWICE in console
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("ROWS", pizzas.count)
return self.pizzas.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Pizza", for: indexPath) as! PizzaTableViewCell
//cell.backgroundColor = Services.baseColor
//cell.pizzaImageView?.image = pizzas[indexPath.row].image
//THESE WORK BUT ARE A STATIC WAY OF SETTING THE CELLS
//CAN ONLY SET THE SELL WITH A SINGLE TEXT LABEL FROM THE DATA ARRAY
cell.imageView?.image = pizzas[indexPath.row].image
cell.textLabel?.text = pizzas[indexPath.row].name
//cell.textLabel?.text = pizzas[indexPath.row].description
//cell.textLabel?.text = "$\(pizzas[indexPath.row].amount)"
// cell.name?.text = pizzas[indexPath.row].name
// cell.imageView?.image = pizzas[indexPath.row].image
// cell.amount?.text = "$\(pizzas[indexPath.row].amount)"
// cell.miscellaneousText?.text = pizzas[indexPath.row].description
//print(cell.name?.text! as Any)
print(cell.imageView as Any)
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100.0
} //END OF
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "pizzaSegue", sender: self.pizzas[indexPath.row] as Pizza)
} //END OF override func tableView
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "pizzaSegue" {
guard let vc = segue.destination as? PizzaViewController else { return }
vc.pizza = sender as? Pizza
}
} //END OF override preppare func
}
class PizzaListTableViewController: UITableViewController {
var pizzas: [Pizza] = []
override func viewDidLoad() {
super.viewDidLoad()
//title you will see on the app screen at the top of the table view
navigationItem.title = "Drink Selection"
tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza")
//tableView.estimatedRowHeight = 134
//tableView.rowHeight = UITableViewAutomaticDimension
fetchInventory { pizzas in
guard pizzas != nil else { return }
self.pizzas = pizzas!
print(self.pizzas)
//self.tableView.reloadData()
//print(self.pizzas)
DispatchQueue.main.async { [weak self] in
self?.tableView.reloadData()
}
}
} //end of viewDidLoad
private func fetchInventory(completion: #escaping ([Pizza]?) -> Void) {
Alamofire.request("http://127.0.0.1:4000/inventory", method: .get)
.validate()
.responseJSON { response in
guard response.result.isSuccess else { return completion(nil) }
guard let rawInventory = response.result.value as? [[String: Any]?] else { return completion(nil) }
let inventory = rawInventory.compactMap { pizzaDict -> Pizza? in
var data = pizzaDict!
data["image"] = UIImage(named: pizzaDict!["image"] as! String)
//print(data)
//print("CHECK")
print("Printing each item: ", Pizza(data: data))
//printing all inventory successful
return Pizza(data: data)
}
completion(inventory)
}
}
#IBAction func ordersButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "orders", sender: nil)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//PRINTING ROWS 0 TWICE in console
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("ROWS", pizzas.count)
return self.pizzas.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Pizza", for: indexPath) as! PizzaTableViewCell
//cell.backgroundColor = Services.baseColor
//cell.pizzaImageView?.image = pizzas[indexPath.row].image
//THESE WORK BUT ARE A STATIC WAY OF SETTING THE CELLS
//CAN ONLY SET THE SELL WITH A SINGLE TEXT LABEL FROM THE DATA ARRAY
cell.imageView?.image = pizzas[indexPath.row].image
cell.textLabel?.text = pizzas[indexPath.row].name
//cell.textLabel?.text = pizzas[indexPath.row].description
//cell.textLabel?.text = "$\(pizzas[indexPath.row].amount)"
// cell.name?.text = pizzas[indexPath.row].name
// cell.imageView?.image = pizzas[indexPath.row].image
// cell.amount?.text = "$\(pizzas[indexPath.row].amount)"
// cell.miscellaneousText?.text = pizzas[indexPath.row].description
//print(cell.name?.text! as Any)
print(cell.imageView as Any)
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100.0
} //END OF
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "pizzaSegue", sender: self.pizzas[indexPath.row] as Pizza)
} //END OF override func tableView
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "pizzaSegue" {
guard let vc = segue.destination as? PizzaViewController else { return }
vc.pizza = sender as? Pizza
}
} //END OF override preppare func
}
struct Pizza {
let id: String
let name: String
let description: String
let amount: Float
//let amount: String
let image: UIImage
init(data: [String: Any]) {
//print("CHECK:: pizza.swift")
self.id = data["id"] as! String
self.name = data["name"] as! String
// self.amount = data["amount"] as! Float
self.amount = ((data["amount"] as? NSNumber)?.floatValue)!
self.description = data["description"] as! String
self.image = data["image"] as! UIImage
}
}
As noted above, I have been able to print the contents of the data array with beer names, pictures, descriptions and etc. I have tried to print to console
print(cell.name?.text)
after setting
cell.name?.text = pizzas[indexPath.row].name
but it prints nil and this is a problem. I have been stuck with this for about 2 weeks!
IBOutlets screenshot:

I think i found your Problem, let me explain
What you are doing here is you have a custom UITableViewCell defined in the Storyboard in a Controller named "Root View Controller" which is not your PizzaListTableViewController to put it simply
And as you said you have absolutely no issue regarding the IBOutlets
Now when you say
tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza")
In Your PizzaListTableViewController you are not linking it with the UI of the cell rather just the Code (This is only used when there is no xib of the cell)
Now what you can do to solve this
Solution # 1
Move/Copy your UI of the PizzaTableViewCell to PizzaListTableViewController in the storyboard from your "Root View Controller"
Make sure you add a Reuse Identifier in the Attribute Inspector of the cell in the storyboard
remove tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza") this wont give you an error this time as it will automatically get register
Make sure all the IBOutlets are connected
Solution # 2
create a separate Nib (xib) of the cell
and now you have to register the cell here like
tableView.register(UINib(nibName: "PizzaTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "PizzaCell")
Hope this helps.

Try this
cell.name?.text = ...
cell.amount?.text = ...
cell.miscellaneousText?.text = ...
cell.pizzaImageView?.image = ...
If it still does not work then make sure your cell and your outlets are not null when setting its value. Hope it helps !

There is something definitely strange going on with your setup.
If you try to name the IBOutlets with the same name as the UITableViewCell default property it'll throw an error. The fact that you were able to set those names and build successfully is strange.
From the screenshot above you can see what happens when I attempted to do this.

Make sure your Table View Controller class is set in the storyboard.
Make sure your Table View Cell class is set in the storyboard.
Make sure that all your outlets are properly connected.
Make sure your Table View Cell Identifier is provided in the storyboard.
My Table View Controller Subclass
My Table View Cell Subclass
cell.imageView?.image and cell.textLabel?.text are optional properties of the table view itself. They are not the properties of the custom cell that you designed.
You use tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza") when you have designed a table view cell in XIB. But as you have designed the cell in the storyboard itself you should set the cell reuse identifier and cell class in the storyboard.
I hope this will help you out.

Related

TableViewCell data transfer but data late arrived in iOS

I am implementing a function that sends the title of the cell to the JSON file name of the next controller when clicking on a data table cell.
The data passes well, but the data arrives one by one late. If you click the first cell, the data is not gone, and if you click the second cell, the contents of the first cell are transferred.
Where do I adjust data going late one by one? Any ideas?
vc1
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let nextViewController: SecondViewController = segue.destination as? SecondViewController else {
return
}
guard let cell: UITableViewCell = sender as? UITableViewCell else {
return
}
nextViewController.title = cell.textLabel?.text
nextViewController.secondAssetName = jsonName
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let country: Countries = countries[indexPath.row]
jsonName = country.asset_name
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countries.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for: indexPath)
let country: Countries = countries[indexPath.row]
cell.imageView?.image = UIImage(named: "flag_" + country.asset_name)
cell.textLabel?.text = country.korean_name
return cell
}
// Data Transfer
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let nextViewController: SecondViewController = segue.destination as? SecondViewController else {
return
}
guard let cell: UITableViewCell = sender as? UITableViewCell else {
return
}
nextViewController.title = cell.textLabel?.text
nextViewController.secondAssetName = jsonName
}
}
vc2
class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var weathers = [Weather]()
var secondAssetName: String?
#IBOutlet weak var tableView: UITableView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let jsonDecoder = JSONDecoder()
guard let dataAsset = NSDataAsset(name: secondAssetName ?? "") else {
return
}
do {
weathers = try jsonDecoder.decode([Weather].self, from: dataAsset.data)
} catch {
print(error.localizedDescription)
}
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return weathers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
let weather: Weather = weathers[indexPath.row]
switch weather.state {
case 10:
cell.cellImageView?.image = UIImage(named: "sunny.png")
case 11:
cell.cellImageView?.image = UIImage(named: "cloudy.png")
case 12:
cell.cellImageView?.image = UIImage(named: "rainy.png")
case 13:
cell.cellImageView?.image = UIImage(named: "snowy.png")
default:
return cell
}
cell.cityNameLabel.text = weather.city_name
cell.temperatureLabel.text = String(weather.celsius)
cell.rainfallProbabilityLabel.text = String(weather.rainfall_probability)
return cell
}
}
Add breakpoints to your code. You should see where the problem is. prepare(for: sender:) is being called before tableView(_: didSelectRowAt:), so the first time you tap a cell, jsonName is nil during prepare, then it gets set during didSelect. The second time you tap it, jsonName has the value from the first tap, then it gets updated after.
Put all of your logic in one place. Remove the didSelect method, and update prepare like so:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let nextViewController: SecondViewController = segue.destination as? SecondViewController else {
return
}
guard let cell: UITableViewCell = sender as? UITableViewCell else {
return
}
guard let indexPath = tableView.indexPath(for: cell) else {
return
}
let country: Countries = countries[indexPath.row]
nextViewController.title = country.korean_name
nextViewController.secondAssetName = country.asset_name
}

iOS multiple JSON file data transfer through segue in Swift

I am trying to make a country weather forecast app, I have vc1 and vc2.
The JSON file to be parsed in vc2 exists for each country, and when the table view cell of vc1 is clicked, we try to implement parsing the JSON file of the country in vc2.
However, I do not know how to pass the JSON file name from vc1 to vc2 through segue.
When passing from vc1 to vc2 using segue, the variable is nil. Is there any solution?
Thanks for reading.
vc1
class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var countries = [Countries]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
let jsonDecoder = JSONDecoder()
guard let dataAsset = NSDataAsset(name: "countries")
else {
return
}
do {
countries = try jsonDecoder.decode([Countries].self, from: dataAsset.data)
} catch {
print(error.localizedDescription)
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countries.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for: indexPath)
let country: Countries = countries[indexPath.row]
cell.imageView?.image = UIImage(named: "flag_" + country.asset_name)
cell.textLabel?.text = country.korean_name
return cell
}
// Data Transfer
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let nextViewController: SecondViewController = segue.destination as? SecondViewController else {
return
}
guard let cell: UITableViewCell = sender as? UITableViewCell else {
return
}
func name(indexPath: IndexPath) {
let country: Countries = countries[indexPath.row]
nextViewController.title = cell.textLabel?.text
nextViewController.secondAssetName = country.asset_name
}
}
}
vc2
class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var weathers = [Weather]()
var secondAssetName: String?
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
let jsonDecoder = JSONDecoder()
guard let dataAsset = NSDataAsset(name: secondAssetName ?? " ") else {
return
}
do {
weathers = try jsonDecoder.decode([Weather].self, from: dataAsset.data)
} catch {
print(error.localizedDescription)
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return weathers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
let weather: Weather = weathers[indexPath.row]
switch weather.state {
case 10:
cell.cellImageView?.image = UIImage(named: "sunny.png")
case 11:
cell.cellImageView?.image = UIImage(named: "cloudy.png")
case 12:
cell.cellImageView?.image = UIImage(named: "rainy.png")
case 13:
cell.cellImageView?.image = UIImage(named: "snowy.png")
default:
return cell
}
cell.cityNameLabel.text = weather.city_name
cell.temperatureLabel.text = String(weather.celsius)
cell.rainfallProbabilityLabel.text = String(weather.rainfall_probability)
return cell
}
}
In VC1, when do you navigate to VC2?
If you have connected the VC1 and VC2 in the storyboard please remove that.
You need to call the "performSegueWithIdentifier" method when the user selects a cell.
For this, you need to implement tableview's didSelectRowAtIndexPath. In this method, you need to call the performSegueWithIdentier method to navigate to vc2.
Also,
In the prepare for segue method, you have this code.
func name(indexPath: IndexPath) {
let country: Countries = countries[indexPath.row]
nextViewController.title = cell.textLabel?.text
nextViewController.secondAssetName = country.asset_name
}
Why do you have it as function? and you are not calling the name function here?
You can move the following code outside the name(index path:) function.
Like so :
// Data Transfer
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let nextViewController: SecondViewController = segue.destination as? SecondViewController else {
return
}
guard let cell: UITableViewCell = sender as? UITableViewCell else {
return
}
let country: Countries = countries[indexPath.row]
nextViewController.title = cell.textLabel?.text
nextViewController.secondAssetName = country.asset_name
}

Issues loading data into UITableView from API call

I am new to ios development and running into issue loading data from an API call to a UITableView. The app is going to serve as ordering system. To get data into each cell of the tableView I have a button on a viewController that sends a post request with the id of the item and the id is matched to items in memory on the server. I have a view controller that has a tableView of the current ordered items which is where my problem is.
I have two other view controllers (BeerListTableViewController and CocktailListTableViewController) with tableViews in them loaded with the items that you can order. These tableViews are loading correctly with their respective items. When pressing on a cell in either tableView I perform a segue to another viewController (BeerDetailViewController or CocktailDetailViewController) where the item is shown and an "Place Order" button is shown. The place order button sends the item to the server where it is added to the array of orders and then popViewController to get back to the tableView. I have verified that the items are getting added correctly. In both BeerListTableViewController and CocktailListTableViewController I have added a barButtonItem "Orders" which segues to DrinkOrderTableView and this is where my ISSUE lies. In this tableView only the orders from BeerDetailViewController are showing. I have included code from the xcode project and my node index.js file. Any help is much appreciated!
class DrinkOrdersTableViewController: UITableViewController {
var orders: [Order] = []
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Current Orders"
fetchAllCurrentOrders { orders in
self.orders = orders!
print(self.orders)
self.tableView.reloadData()
}
}
private func fetchAllCurrentOrders(completion: #escaping([Order]?) -> Void) {
Alamofire.request("http://127.0.0.1:4000/orders", method: .get)
.validate()
.responseJSON { response in
guard response.result.isSuccess else { return completion(nil) }
guard let rawInventory = response.result.value as? [[String: Any]?] else { return completion(nil) }
let currentOrders = rawInventory.compactMap { ordersDict -> Order? in
guard let orderId = ordersDict!["id"] as? String,
let orderStatus = ordersDict!["status"] as? String,
var pizza = ordersDict!["pizza"] as? [String: Any] else { return nil }
pizza["image"] = UIImage(named: pizza["image"] as! String)
return Order(
id: orderId,
pizza: Pizza(data: pizza),
status: OrderStatus(rawValue: orderStatus)!
)
}
completion(currentOrders)
}
}
#IBAction func closeButtonPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("Debugging ROWS", orders.count)
return orders.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "order", for: indexPath)
let order = orders[indexPath.row]
cell.textLabel?.text = order.pizza.name
cell.imageView?.image = order.pizza.image
cell.detailTextLabel?.text = "$\(order.pizza.amount) - \(order.status.rawValue)"
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100.0
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "orderSegue", sender: orders[indexPath.row] as Order)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "orderSegue" {
guard let vc = segue.destination as? OrderViewController else { return }
vc.order = sender as? Order
}
}
}
link to server code
Link to screencap of issue

Issue loading data from array to UITableView cells

I am very new to swift programming and trying to build an app to take orders and relay them to an admin app. My data is not loading in my UITableView and I'm not sure why, as far as I can tell I've done everything by the book. I am loading data from a node server I created and when printing the contents of the array all items are printed as key,pair values. The UIimages are loading in each of the tableView cells but the labels are not and after setting the labels and printing them, the values are still nil of the labels.
I created a TableView class called PizzaListTableViewController and a custom TableViewCell class called PizzaTableViewCell. I have added a UIimage and three labels in the storyboard interface builder.
Structure is: ViewController > TableView > TableViewCell > Image, Labels
My main VC is connected to its ViewController.class
My TableViewCell is connected to its TableViewCell.class
I have an identifier and linked it up, as per code below
I linked all the outlets. Any help would be greatly appreciated!
I have tried to rewrite the classes, break all outlet connections and reconnect them, assign values in the method where the labels are set but no luck with anything.
class PizzaListTableViewController: UITableViewController {
var pizzas: [Pizza] = []
override func viewDidLoad() {
super.viewDidLoad()
//title you will see on the app screen at the top of the table view
navigationItem.title = "Drink Selection"
//tableView.estimatedRowHeight = 134
//tableView.rowHeight = UITableViewAutomaticDimension
fetchInventory { pizzas in
guard pizzas != nil else { return }
self.pizzas = pizzas!
//print(self.pizzas)
self.tableView.reloadData()
//print(self.pizzas)
}
} //end of viewDidLoad
private func fetchInventory(completion: #escaping ([Pizza]?) -> Void) {
Alamofire.request("http://127.0.0.1:4000/inventory", method: .get)
.validate()
.responseJSON { response in
guard response.result.isSuccess else { return completion(nil) }
guard let rawInventory = response.result.value as? [[String: Any]?] else { return completion(nil) }
let inventory = rawInventory.compactMap { pizzaDict -> Pizza? in
var data = pizzaDict!
data["image"] = UIImage(named: pizzaDict!["image"] as! String)
//print(data)
//print("CHECK")
print("Printing all data: ", Pizza(data: data))
//printing all inventory successful
return Pizza(data: data)
}
//self.tableView.reloadData()
completion(inventory)
}
}
#IBAction func ordersButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "orders", sender: nil)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//PRINTING ROWS 0 TWICE in console
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//print("ROWS", pizzas.count)
return self.pizzas.count
}
//THIS IS WHERE THE CELL IDENTIFIER IS ??
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//print("IN CELLFORROWAT")
tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "cell")
let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PizzaTableViewCell
//cell.backgroundColor = Services.baseColor
cell.name?.text = pizzas[indexPath.row].name
cell.imageView?.image = pizzas[indexPath.row].image
cell.amount?.text = "$\(pizzas[indexPath.row].amount)"
cell.miscellaneousText?.text = pizzas[indexPath.row].description
print(cell.name?.text! as Any)
print(cell.imageView as Any)
//print("END CELLFORROWAT")
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100.0
} //END OF
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "pizza", sender: self.pizzas[indexPath.row] as Pizza)
} //END OF override func tableView
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "pizza" {
guard let vc = segue.destination as? PizzaViewController else { return }
vc.pizza = sender as? Pizza
}
} //END OF override preppare func
}
class PizzaTableViewCell: UITableViewCell {
#IBOutlet weak var name: UILabel!
#IBOutlet weak var pizzaImageView: UIImageView!
#IBOutlet weak var amount: UILabel!
#IBOutlet weak var miscellaneousText: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
//Configure the view for the selected state
}
}
struct Pizza {
let id: String
let name: String
let description: String
let amount: Float
let image: UIImage
init(data: [String: Any]) {
//print("CHECK:: pizza.swift")
self.id = data["id"] as! String
self.name = data["name"] as! String
// self.amount = data["amount"] as! Float
self.amount = ((data["amount"] as? NSNumber)?.floatValue)!
self.description = data["description"] as! String
self.image = data["image"] as! UIImage
}
}
I have also printed values of the array to console and the data is printing as expected but values of cell.name?.text, cell.amount?.text, and cell.miscellaneousText?.text print nil.
Please try to reload your tableview in Main thread inside the code that you pass as a parameter to fetchInventory:
DispatchQueue.main.async {
self.tableView.reloadData()
}
So, your fetchInventory call should become:
fetchInventory { pizzas in
guard pizzas != nil else { return }
self.pizzas = pizzas!
//print(self.pizzas)
DispatchQueue.main.async {
self.tableView.reloadData()
}
//print(self.pizzas)
}
Please avoid to do UI work from a background thread because it is not correct/safe. Also, you may try to set self?.pizzas too inside that main thread block.
And please take into account Alan's advice on double call.
Please remove completely the register from tableView/cellForRow.
// tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "cell")
Instead of:
cell.imageView?.image = pizzas[indexPath.row].image
put:
cell.pizzaImageView?.image = pizzas[indexPath.row].image
This is your outlet name.
Please check my test below that is working :
import UIKit
class PizzaListTableViewController: UITableViewController {
var pizzas: [Pizza] = []
override func viewDidLoad() {
super.viewDidLoad()
//title you will see on the app screen at the top of the table view
navigationItem.title = "Drink Selection"
//tableView.estimatedRowHeight = 134
//tableView.rowHeight = UITableViewAutomaticDimension
fetchInventory { pizzas in
guard pizzas != nil else { return }
self.pizzas = pizzas!
print(self.pizzas)
DispatchQueue.main.async {
self.tableView.reloadData()
}
//print(self.pizzas)
}
} //end of viewDidLoad
private func fetchInventory(completion: #escaping ([Pizza]?) -> Void) {
let rawInventory0 = [
[
"id": "1",
"name": "name1",
"amount": 1234,
"description": "description1",
"image": "image1"
],
[
"id": "2",
"name": "name2",
"amount": 1235,
"description": "description2",
"image": "image2"
],
[
"id": "3",
"name": "name3",
"amount": 1236,
"description": "description3",
"image": "image3"
],
[
"id": "4",
"name": "name4",
"amount": 1237,
"description": "description4",
"image": "image4"
]
] as? [[String: Any]?]
guard let rawInventory1 = rawInventory0 as? [[String: Any]?] else { return completion(nil) }
let inventory = rawInventory1.compactMap { pizzaDict -> Pizza? in
var data = pizzaDict!
data["image"] = UIImage(named: pizzaDict!["image"] as! String)
print(data)
print("CHECK")
print("Printing all data: ", Pizza(data: data))
//printing all inventory successful
return Pizza(data: data)
}
//self.tableView.reloadData()
completion(inventory)
}
// MARK: - Table view data source
#IBAction func ordersButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "orders", sender: nil)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//PRINTING ROWS 0 TWICE in console
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//print("ROWS", pizzas.count)
return self.pizzas.count
}
//THIS IS WHERE THE CELL IDENTIFIER IS ??
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//print("IN CELLFORROWAT")
// tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "cell")
let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PizzaTableViewCell
//cell.backgroundColor = Services.baseColor
cell.name?.text = pizzas[indexPath.row].name
cell.pizzaImageView?.image = pizzas[indexPath.row].image
cell.amount?.text = "\(pizzas[indexPath.row].amount)"
cell.miscellaneousText?.text = pizzas[indexPath.row].description
print(cell.name?.text! as Any)
//print(cell.imageView as Any)
//print("END CELLFORROWAT")
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100.0
} //END OF
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "pizza", sender: self.pizzas[indexPath.row] as Pizza)
} //END OF override func tableView
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "pizza" {
guard let vc = segue.destination as? PizzaViewController else { return }
vc.pizza = sender as? Pizza
}
} //END OF override preppare func
}

TableView not loading cells

My table view isn't loading the custom cells that are put into an array when I do a certain function. I know the the array contains the cells, but am at a loss as to why the cells aren't showing. It did work before but I made a few changes elsewhere in the code and now it does not work. Below is the code where I believe the error might possibly be:
#IBOutlet weak var incomeExpenseTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
incomeExpenseTableView.reloadData()
incomeExpenseTableView.delegate = self
incomeExpenseTableView.dataSource = self
}
override func viewDidAppear(animated: Bool) {
incomeExpenseTableView.reloadData()
}
#IBAction func addButtonPressed(sender: AnyObject) {
let addMessage = SCLAlertView()
addMessage.addButton("Income") {
self.performSegueWithIdentifier("incomeSegue", sender: self)
}
addMessage.addButton("Expense") {
self.performSegueWithIdentifier("expenseSegue", sender: self)
}
addMessage.showInfo("New Entry", subTitle: "Select either an income or expense to add")
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let post = DATA_KEY._loadedPosts[indexPath.row]
if let cell = tableView.dequeueReusableCellWithIdentifier("IncomeExpenseCell") as? IncomeExpenseCell {
cell.configureCell(post)
return cell
} else {
let cell = IncomeExpenseCell()
cell.configureCell(post)
return cell
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DataService.instance._loadedPosts.count
}
func onPostsLoaded(notif: AnyObject) {
incomeExpenseTableView.reloadData()
}
FYI DATA_KEY = DataService.instance
Thanks
if you have a tableviewcell's identifier named "IncomeExpenseCell", the "if let" will always be successful, why using else, you can use as! instead of as?, you don't need 'else' here, and IncomeExpenseCell() maybe will not satisfy your 'cell init'
if let cell = tableView.dequeueReusableCellWithIdentifier("IncomeExpenseCell") as? IncomeExpenseCell {
cell.configureCell(post)
return cell
}
let cell = tableView.dequeueReusableCellWithIdentifier("IncomeExpenseCell") as! IncomeExpenseCell {
cell.configureCell(post)
return cell
}

Resources