How to iterate through Dictionary of Dictionary Values in UITableViewCell? - ios

This is my first post and I hope its a great question because iv been stuck on this for days. (Literally searched every related question and found nothing that I could add up for a solution.)
Basically I'm building a pure Swift application. My problem is that I cant figure out how to place each dictionary values into each UITableCell that is created.
Also the JSON response from the GET creates a NSCFDictionary type.
UITableViewCell Properties
UILabel - Holds the Offer "name"
UI Label #2 - Holds Offer "description"
UIImage - Holds the Offer "thumb_url"
So basically I need to store each offer object's (name, description, thumb_url) in every UITableViewCell that the ViewController creates.
GET Request
import UIKit
class freeIAPCell: UITableViewCell {
#IBOutlet weak var aName: UILabel!
#IBOutlet weak var aDescription: UILabel!
#IBOutlet weak var aImage: UIImageView!
}
class FreeIAPViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// Everbadge Request
var apiURL = "apiurlhere"
var parsedArray: [[String:String]] = []
func queryEB() {
// Query DB Here
// Store the API url in a NSURL Object
let nsURL = NSURL(string: apiURL)
let request = NSMutableURLRequest(URL: nsURL!)
request.HTTPMethod = "GET"
// Execute HTTP Request
let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!) {
data, response, error in
if error != nil {
print("Error = \(error)")
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary
print(json.isKindOfClass(NSDictionary)) // true
let data = json.objectForKey("data") as! NSDictionary
//print(data)
let m = data.objectForKey("offers") as! NSArray
print(m)
print(m.valueForKeyPath("name"))
self.parsedArray = m as! [[String : String]]
} catch {
print("THERE WAS AN ERROR PARSING JSON FOR EVERBADGE")
}
}
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
queryEB()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
// MARK: UITableView method implementation
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("freeAppCell", forIndexPath: indexPath) as! freeIAPCell
let obj = parsedArray[indexPath.row] // fatal error: Index out of range
cell.aName.text = obj["name"]
return cell
}
}
API Request Data Structure (print(m))
(
{
"name" = "Mate";
id = 23941;
description = "10-20 word description goes here"
"url" = "google.com
"ver" = "0.12"
price = "0.17"
"public_name" = "Good Ole Mate"
"thumb_url" = "http://google.com/mate.jpg
};
{
"name" = "Mate";
id = 23941;
description = "10-20 word description goes here"
"url" = "google.com
"ver" = "0.12"
price = "0.17"
"public_name" = "Good Ole Mate"
"thumb_url" = "http://google.com/mate.jpg
};
{
"name" = "Mate";
id = 23941;
description = "10-20 word description goes here"
"url" = "google.com
"ver" = "0.12"
price = "0.17"
"public_name" = "Good Ole Mate"
"thumb_url" = "http://google.com/mate.jpg
};
{
"name" = "Mate";
id = 23941;
description = "10-20 word description goes here"
"url" = "google.com
"ver" = "0.12"
price = "0.17"
"public_name" = "Good Ole Mate"
"thumb_url" = "http://google.com/mate.jpg
};
{
"name" = "Mate";
id = 23941;
description = "10-20 word description goes here"
"url" = "google.com
"ver" = "0.12"
price = "0.17"
"public_name" = "Good Ole Mate"
"thumb_url" = "http://google.com/mate.jpg
};
);

First create public arrays for your 3 items...
var nameArray = [String]()
var descriptionArray = [String]()
var thumbnailArray = [String]()
Then loop through your json parse like this....
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! NSDictionary
if responseString != nil
{
let items: AnyObject! = responseString["items"] as AnyObject!
if items != nil
{
// Loop through all search results and keep just the necessary data.
for var i=0; i<items.count; ++i
{
if let names = items[i]["name"] as? NSDictionary
{
let name = names as! String
self.nameArray.append(name)
}
if let descriptions = items[i]["description"] as? NSDictionary
{
let description = descriptions as! String
self.descriptionArray.append(description)
}
if let thumbnails = items[i]["thumb_url"] as? NSDictionary
{
let thumbnail = thumbnails as! String
self.thumbnailArray.append(thumbnail)
}
}
}
self.resultsTableView.reloadData()
Create an OfferTableViewCell Class with a nameLabel:UILabel, descriptionLabel:UILabel, and thumbnailImage:UIImage. Finally in your cellForRowAtIndexPath.....
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("offer", forIndexPath: indexPath) as! OfferTableViewCell
cell.nameLabel.text = self.nameArray[indexPath.row]
cell.descriptionLabel.text = self.descriptionArray[indexPath.row]
let url = NSURL(string: self.thumbnailArray[indexPath.row])
let data = NSData(contentsOfURL: url!)
cell.thumbnailImage.image = UIImage(data: data!)
return cell
}

Related

add the values according to appending the values

How to add the values according to appending the values in swift3.
this is my datasource:-
class QM_ChartDataSourceModel: NSObject {
var dataListArray:Array<QM_CartModel>? = []
init(array :Array<[String:Any]>?) {
super.init()
var newArray:Array<[String:Any]> = []
if array == nil{
newArray = self.getJsonDataStored22()
}
else{
newArray = array!
}
var datalist:Array<QM_CartModel> = []
for dict in newArray{
let model = QM_CartModel(dictionary: dict)
datalist.append(model!)
}
self.dataListArray = datalist
}
}
typealias dummyDataSource22 = QM_ChartDataSourceModel
extension dummyDataSource22{
func getJsonDataStored22() ->Array<Dictionary<String,String>>{
let jsonArray = [["id":"311","name":"Dosa Fest","price":"QR 40","quantity":"3"],["id":"312","name":"Organic Vegan Fest","price":"QR 40","quantity":"2"],["id":"313","name":"Food Of Life Time","price":"QR 56","quantity":"7"],["id":"314","name":"Tea Time","price":"QR 88","quantity":"1"],["id":"315","name":"Dosa Fest","price":"QR 13","quantity":"6"],["id":"316","name":"Organic Vegan Fest","price":"QR 4","quantity":"8"],["id":"317","name":"Food Of Life Time","price":"QR 90","quantity":"3"],["id":"318","name":"Tea Time","price":"QR 66","quantity":"2"],["id":"319","name":"Dosa Fest","price":"QR 81","quantity":"6"],["id":"320","name":"Organic Vegan Fest","price":"QR 49","quantity":"2"]] as Array<Dictionary<String,String>>
return jsonArray
}
}
in tableviewcell:
func setEventData(carts:QM_CartModel)
{
self.name.text = carts.cartname
self.price.text = carts.cartsum
self.itemQuantityStepper.value = 1
setItemQuantity(quantity)
print(self.price.text)
let value = carts.cartsum
let x: Int? = Int(value!)
print(x)
let add = x!
print(add)
let theIntegerValue1 :Int = add
let theStringValue1 :String = String(theIntegerValue1)
self.price.text = theStringValue1
}
my model:-
class QM_CartModel: NSObject {
var cartname :String!
var cartprice:String!
var cartquantity:String!
var carttotalprice:String!
var carttotal:String!
var cartQR:String!
var cartvalue:String!
var cartsum:String?
var cartid:String!
init?(dictionary :JSONDictionary) {
guard let name = dictionary["name"] as? String else {
return
}
if let quantity = dictionary["quantity"] as? String{
let price = dictionary["price"] as? String
let id = dictionary["id"] as? String
self.cartid = id
self.cartprice = price
self.cartquantity = quantity
let fullNameArr = price?.components(separatedBy: " ")
let QR = fullNameArr?[0]
let value = fullNameArr?[1]
self.cartQR = QR
self.cartvalue = value
let x: Int? = Int(value!)
print(x)
let y:Int? = Int(quantity)
print(y)
let sum = x! * y!
print(sum)
let sum1 = String(describing: sum)
cartsum = sum1
}
my viewmodel:-
class QM_ChartViewModel: NSObject {
var datasourceModel:QM_ChartDataSourceModel
var insertedArray:QM_CartModel?
var filteredListArray:Array<QM_CartModel>? = []
var totalListArray:Array<QM_CartModel>? = []
init(withdatasource newDatasourceModel: QM_ChartDataSourceModel) {
datasourceModel = newDatasourceModel
print(datasourceModel.dataListArray)
}
func datafordisplay(atindex indexPath: IndexPath) -> QM_CartModel{
return datasourceModel.dataListArray![indexPath.row]
}
func numberOfRowsInSection(section:Int) -> Int {
return datasourceModel.dataListArray!.count
}
func delete(atIndex indexPath: IndexPath) {
datasourceModel.dataListArray!.remove(at: indexPath.row)
}
func search(idsearch :String?) {
filteredListArray = datasourceModel.dataListArray?.filter{($0.cartid?.range(of: idsearch!, options: .caseInsensitive) != nil)}
print(filteredListArray)
}
func searchindex(objectatindex index: Int) -> QM_CartModel {
return self.filteredListArray![index]
}
func total()
{ totalListArray = datasourceModel.dataListArray?.filter{($0.cartsum != nil)}
print(totalListArray)
}
func add(){
datasourceModel.dataListArray?.append(insertedArray!)
print(datasourceModel.dataListArray)
print(insertedArray?.offerAddName)
print(insertedArray?.offerprice)
self.datasourceModel.dataListArray = datasourceModel.dataListArray
print(insertedArray?.cartsum)
}
func addquantity(quantity:Int)
{
// datasourceModel.dataListArray?.filter{ $0.cartid! == cartaddedid! }.first?.qty = quantity as NSNumber?
}
}
in viewcontroller my code as below:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return chartViewModel.numberOfRowsInSection(section: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "cell"
var cell: QM_ChartCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? QM_ChartCell
if cell == nil {
tableView.register(UINib(nibName: "QM_ChartCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? QM_ChartCell
}
cell.setEventData(carts: chartViewModel.datafordisplay(atindex: indexPath))
print(cell.numbers)
see here can see the total.So that way i need to display the total
this is my code ...here i getting the values model.cartsum.So this value is appending in var number:[String] = []
.But here i need-as values are appending ,here i need to add the number.So first value is 1 and second value is 2 then i need to add this values.And if next number is 3 then i need to get sum = 6.
How to get
You need to calculate all the cart stuff just after you get it either from service or from local. You don't need to do calculation in cellForRowAtIndex: method because it should be done once.
I assume this is your data structure as mentioned in question.
let jsonArray = [["id":"311","name":"Dosa Fest","price":"QR 40","quantity":"3"],
["id":"312","name":"Organic Vegan Fest","price":"QR 40","quantity":"2"],
["id":"313","name":"Food Of Life Time","price":"QR 56","quantity":"7"],
["id":"314","name":"Tea Time","price":"QR 88","quantity":"1"],
["id":"315","name":"Dosa Fest","price":"QR 13","quantity":"6"],
["id":"316","name":"Organic Vegan Fest","price":"QR 4","quantity":"8"],
["id":"317","name":"Food Of Life Time","price":"QR 90","quantity":"3"],
["id":"318","name":"Tea Time","price":"QR 66","quantity":"2"],
["id":"319","name":"Dosa Fest","price":"QR 81","quantity":"6"],
["id":"320","name":"Organic Vegan Fest","price":"QR 49","quantity":"2"]]
Here is how to calculate the total of the cart. As per your data considering price is in Int
var total = 0
for item in jsonArray {
/// Will check if quantity is available in dictionary and convertible into an Int else will be 0
let quantity = Int(item["quantity"] ?? "0") ?? 0
/// Will check price key exists in the dictionary
if let priceStr = item["price"] {
/// Will fetch the last components and check if it is convertible into an Int else 0
let price = Int(priceStr.components(separatedBy: " ").last ?? "0") ?? 0
/// Multiply price with quantity and add into total
total += price * quantity
}
}
print(total)
Output: 1776
Another way:
let total = jsonArray.map { (item) -> Int in
let quantity = Int(item["quantity"] ?? "0") ?? 0
let price = Int(item["price"]?.components(separatedBy: " ").last ?? "0") ?? 0
return quantity * price
}.reduce(0, +)
print(total)
Please try this code if you have array of Int
var arrayOfInt = [2,3,4,5,4,7,2]
let reducedNumberSum = arrayOfInt.reduce(0,+)
print(reducedNumberSum)
Answer: 27
In your code
let model = chartViewModel.datafordisplay(atindex: indexPath)
Please describe more so we can answer according your problem.

How to show image from json in table view

To get data the from json class is created
class getData: NSObject {
var descriptionn : String = ""
var image : String = ""
// static let shared = getData()
func getDataForTableView(results: [[String:String]], index : Int){
var productArray = [String:String]()
productArray = results[index]
descriptionn = productArray["description"]!
image = productArray["images"]!
}
}
To display data in table view
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "discoveryNewscell") as! DiscoveryNewsTableViewCell
// if results.count > 0{
classObject.getDataForTableView(results: results, index: indexPath.row)
cell.sneakerImageView.image=filteredsneakernews[indexPath.row].image
print("abc image"+classObject.image)
cell.newsTitle.text = classObject.descriptionn
// }
return cell
}
The json is following foramt
ptional({
data = (
{
"created_date" = "2017-11-09 14:58:58";
"created_on" = "2017-11-09";
"createdd_by" = 3;
description = dfdfdsdfsdfs;
id = 4;
images = "7a53f87882409c4622a0977d5026038b.jpg";
likes = 25;
product = 12;
status = 1;
title = facebook;
"title_keys" = fac;
type = News;
},
{
"created_date" = "2017-11-15 14:33:01";
"created_on" = "2017-11-23";
"createdd_by" = 3;
description = dfdfdf;
id = 7;
images = "e626b8003e6e08df874e33556e7f6e69.jpg";
likes = 3;
product = 0;
status = 1;
title = don;
"title_keys" = don;
type = News;
},
{
"created_date" = "2017-11-16 10:34:48";
"created_on" = "2017-11-13";
"createdd_by" = 3;
description = "my first computer";
id = 8;
images = "556b1855de039b8d99bc787acd103262.jpg";
likes = 90;
product = 13;
status = 1;
title = Dell;
"title_keys" = dell;
type = News;
},
{
"created_date" = "2018-01-02 16:23:54";
"created_on" = "2018-01-08";
"createdd_by" = 3;
description = sdfsdfsfdf;
id = 14;
images = "0c980d3f9cd0393a46bb04995d16177a.jpg";
likes = 0;
product = 0;
status = 1;
title = dfsfdsfdfs;
"title_keys" = " dfsfdsfdfs";
type = News;
}
);
message = "Success.";
newsurl = "http://dev.nsol.sg/projects/sneakers/assets/brand_images/thumb/";
success = 1;
})
This json has image of following from
images = "7a53f87882409c4622a0977d5026038b.jpg";
How to display the image .Image(classObject.image) in string format how to display image view on table view ?you can download the code from this link .https://drive.google.com/file/d/1bVQsuSQINSa6YRwZe2QwEjPpU_m7S3b8/view?usp=sharing
Image path should be like URL format. http://dev.nsol.sg/projects/sneakers/assets/brand_images/thumb/7a53f87882409c4622a0977d5026038b.jpg.
yourJSON
message = "Success.";
newsurl = "http://dev.nsol.sg/projects/sneakers/assets/brand_images/thumb/";
success = 1;
Global Declaration:
var imgURLStringArr = [String]()
func appendURLPathFromJSON(jsonDict: NSDictionary)
{
let urlPath : String = jsonDict.value(forKey: "newsurl") as! String
let dataArr : NSArray = jsonDict.value(forKey: "data") as! NSArray
for i in 0..<dataArr.count
{
let dataDict : NSDictionary = dataArr[i] as! NSDictionary
let imageStr : String = dataDict.value(forKey: "images") as! String
let appendPath : String = urlPath + imageStr
imgURLStringArr.append(appendPath)
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
print("willDisplaywillDisplay")
let cell = cell as! DiscoveryNewsTableViewCell
URLSession.shared.dataTask(with: NSURL(string: self.imgURLStringArr[indexPath.row])! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error ?? "No Error")
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
cell.thumbImg.image = image
})
}).resume()
}

How to sort A - z in table view swift 2.0

i have one table view, which will dipslay the json data from one url.Its all working fine. What i need is?. in my table view i have one lable called "name label ".Which will display the name in my table view.
And i have one menu option with one button name called" sort data A - z ".When i click that, my table view data should reload with sorting the date from A-z alphabets order ( My name title ).
This is my button action :
#IBAction func sortByAZBtnPress(sender: AnyObject) {
}
My viewcontroller.swift
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var RightMenu: UIView!
#IBOutlet weak var tableView: UITableView! // UITable view declaration
#IBOutlet weak var Resultcount: UILabel! // count label
var arrDict :NSMutableArray=[] // array to store the value from json
let cellSpacingHeight: CGFloat = 5 // cell spacing from each cell in table view
override func viewDidLoad() {
super.viewDidLoad()
self.jsonParsingFromURL() // call the json method
let nib = UINib(nibName:"customCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
RightMenu.layer.borderWidth = 1
}
// web services method
func jsonParsingFromURL () {
let url = NSURL(string: "http://sampleUrl.com”)
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
{
dispatch_async(dispatch_get_main_queue()){
self.arrDict=(try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSMutableArray
//print(self.arrDict)
if (self.arrDict.count>0)
{
self.Resultcount.text = "\(self.arrDict.count) Results"
self.tableView.reloadData()
}}
// arrDict.addObject((dict.valueForKey("xxxx")
}
}
dataTask.resume()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.arrDict.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
// calling each cell based on tap and users ( premium / non premium )
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:customCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! customCell
cell.vendorName.text=arrDict[indexPath.section] .valueForKey("name") as? String
cell.vendorAddress.text=arrDict[indexPath.section] .valueForKey("address") as? String
return cell
}
// MARK:
// MARK: Sort Method
#IBAction func sortByRevBtnPress(sender: AnyObject) {
self.indicator.startAnimating()
self.indicator.hidden = false
RightMenu.hidden = true
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue()){
self.indicator.stopAnimating()
self.indicator.hidden = true
};
self.tableView.reloadData()
}
#IBAction func sortByAZBtnPress(sender: AnyObject) {
}
}
Please help me out. I am not getting clear idea to do that...Thanks
Updated :
(
{
ad = 0;
address = "900 York Mills Rd, Toronto, ON M3B 3H2, Canada";
"category_id" = 1;
latitude = "43.7563";
longitude = "-79.3495";
name = "Honeybee Restaurant";
phone = 9876543210;
rating = "5.0";
},
{
ad = 1;
address = "1677 Wilson Ave, Toronto, ON M3L 1A5, Canada";
"category_id" = 1;
latitude = "43.7194";
longitude = "-79.5153";
name = "Maki My Way";
phone = 9875463254;
rating = "4.0";
},
{
ad = 1;
address = "75 Bremner Blvd, Toronto, ON M5J 0A1, Canada";
"category_id" = 1;
latitude = "43.6429";
longitude = "-79.3814";
name = "Blow Fish Restaurant";
phone = 9873245610;
rating = "5.0";
},
{
ad = 0;
address = "4150 Yonge St, Toronto, ON M2P 2C6, Canada";
"category_id" = 1;
latitude = "43.747";
longitude = "-79.4079";
name = "SaigonFlower Restaurant";
phone = 7892345621;
rating = "3.0";
},
{
ad = 1;
address = "604 King St W, Toronto, ON M5V 1M6, Canada";
"category_id" = 1;
latitude = "43.6445";
longitude = "-79.4004";
name = "Sushi Gen";
phone = 7456321065;
rating = "2.0";
},
)
Assuming that your array is an array of dictionaries and your dictionary has a "Name" key you can do this. Change the code if your dict has different keys that contains the name.
#IBAction func sortByAZBtnPress(sender: AnyObject) {
arrDict.sortUsingComparator { (dict1, dict2) -> NSComparisonResult in
if let name1 = dict1["name"] as? String, name2 = dict2["name"] as? String {
return name1.compare(name2)
}
return .OrderedAscending
}
self.tableView.reloadData()
}
For order by rating (High to low) you can use this.
arrDict.sortUsingComparator { (dict1, dict2) -> NSComparisonResult in
if let name1 = dict1["rating"] as? String, name2 = dict2["rating"] as? String {
return name2.compare(name1)
}
return .OrderedAscending
}
For sorting of the tableview you should sort youre dataSource firstly and than reload tableview.
In you're case:
Firstly sort by A to z:
arrDict
For sorting use functional programming:
arrDict = arrDict.sort({ $0.name > $1.name })
Secondly reload tableview by:
self.tableView.reloadData()
sort arrDict using below code then self.tableView.reloadData():
sortedArray = [anArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];

How to filter an array of JSON objects to be used in a table view?

I'm getting JSON data from an API and parsing that data in objects, which are then simply stored in an array of objects. The objects themselves contain data about articles from a newspaper. However, I need to filter that data. Some of the objects I'm getting from my JSON actually have no article content because they are pictures and not articles (i.e. some of the "nodes" from the API's JSON have content that I don't want to see in my table view).
In my JSON-parsing function, I've tried to make it so that the parsed object will only get added to the array of parsed objects if the character count of the "articleContent" variable is above 40. Here is what it looked like.
if issueElement.articleContent.characters.count > 40 {
self.currentIssueObjects.addObject(issueElement)
}
However, this simply does not work. I get the typical "unexpectedly found nil while unwrapping an Optional value" error message (I don't get a specific line for the error). How can I make this work ? I'm essentially trying to prevent the array from having objects with empty articleContent, because then that screws up my table view (empty cells, duplicates, etc...).
Here is my cellForRowAtIndexPath code, and my JSON-parsing code:
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell {
let row = indexPath.row
guard let cell = tableView.dequeueReusableCellWithIdentifier(CurrentIssueArticlesTableCellIdentifier, forIndexPath: indexPath) as? CurrentIssueArticlesTableViewCell else {
print ("error: currentIssueTableView cell is not of class CurrentIssueArticlesTableViewCell, we will use EditorialsTableViewCell instead")
return tableView.dequeueReusableCellWithIdentifier(CurrentIssueArticlesTableCellIdentifier, forIndexPath: indexPath) as! EditorialsTableViewCell
}
let currentIssueObject = currentIssueObjects.objectAtIndex(indexPath.row) as! IssueElement
let title = currentIssueObject.title ?? ""
let timeStampDateObject = NSDate(timeIntervalSince1970: NSTimeInterval(currentIssueObject.timeStamp))
let timeStampDateString = dateFormatter.stringFromDate(timeStampDateObject) ?? "Date unknown"
if let author = currentIssueObject.author {
cell.currentIssueArticlesAuthorLabel!.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
cell.currentIssueArticlesAuthorLabel!.text = author
}
let issueNumber = currentIssueObject.issueNumber ?? ""
let volumeNumber = currentIssueObject.volumeNumber ?? ""
let articleContent = currentIssueObject.articleContent ?? ""
let nodeID = currentIssueObject.nodeID ?? 0
cell.currentIssueArticlesHeadlineLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
cell.currentIssueArticlesHeadlineLabel.text = title
cell.currentIssueArticlesPublishDateLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
cell.currentIssueArticlesPublishDateLabel.text = timeStampDateString
if row == 0 {
cell.userInteractionEnabled = false
let imageURL = (currentIssueObjects.objectAtIndex(row) as! IssueElement).imageURL
cell.currentIssueArticlesHeadlineLabel.textColor = UIColor.clearColor()
cell.currentIssueArticlesAuthorLabel.textColor = UIColor.clearColor()
cell.currentIssueArticlesPublishDateLabel.textColor = UIColor.clearColor()
cell.request?.cancel()
if let image = self.imageCache.objectForKey(imageURL!) as? UIImage {
cell.currentIssueArticlesBackgroundImageView.image = image
} else {
cell.currentIssueArticlesBackgroundImageView.image = UIImage(named: "reveal Image")
cell.request = Alamofire.request(.GET, imageURL!).responseImage() { response in
if response.result.error == nil && response.result.value != nil {
self.imageCache.setObject(response.result.value!, forKey: response.request!.URLString)
cell.currentIssueArticlesBackgroundImageView.image = response.result.value
} else {
}
}
}
cell.currentIssueArticlesBackgroundImageView.hidden = false
}
else {
cell.currentIssueArticlesBackgroundImageView.hidden = true
}
return cell
}
JSON-parsing code:
func populateCurrentIssue() {
if populatingCurrentIssue {
return
}
populatingCurrentIssue = true
self.cellLoadingIndicator.backgroundColor = goldenWordsYellow
self.cellLoadingIndicator.startAnimating()
Alamofire.request(GWNetworking.Router.Issue).responseJSON() { response in
if let JSON = response.result.value {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
var nodeIDArray : [Int]
if (JSON .isKindOfClass(NSDictionary)) {
for node in JSON as! Dictionary<String, AnyObject> {
let nodeIDValue = node.0
var lastItem : Int = 0
self.nodeIDArray.addObject(nodeIDValue)
if let issueElement : IssueElement = IssueElement(title: "Could not retrieve title", nodeID: 0, timeStamp: 0, imageURL: "init", author: "Author not found", issueNumber: "Issue # error", volumeNumber: "Volume # error", articleContent: "Could not retrieve article content", coverImageInteger: "init", coverImage: UIImage()) {
issueElement.title = node.1["title"] as! String
issueElement.nodeID = Int(nodeIDValue)!
let timeStampString = node.1["revision_timestamp"] as! String
issueElement.timeStamp = Int(timeStampString)!
issueElement.imageURL = String(node.1["image_url"])
if let author = node.1["author"] as? String {
issueElement.author = author
}
if let issueNumber = node.1["issue_int"] as? String {
issueElement.issueNumber = issueNumber
}
if let volumeNumber = node.1["volume_int"] as? String {
issueElement.volumeNumber = volumeNumber
}
if let articleContent = node.1["html_content"] as? String {
issueElement.articleContent = articleContent
}
issueElement.coverImageInteger = String(node.1["cover_image"]) // addition specific to the Current Issue View Controller
lastItem = self.currentIssueObjects.count
print(issueElement.nodeID)
if issueElement.articleContent.characters.count > 40 {
self.currentIssueObjects.addObject(issueElement)
print(issueElement.nodeID)
}
// Sorting with decreasing timestamp from top to bottom.
let timestampSortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
self.currentIssueObjects.sortUsingDescriptors([timestampSortDescriptor])
// Placing the object with coverImage
let coverImageSortDescriptor = NSSortDescriptor(key: "coverImageInteger", ascending: false)
self.currentIssueObjects.sortUsingDescriptors([coverImageSortDescriptor])
let indexPaths = (lastItem..<self.currentIssueObjects.count).map {
NSIndexPath(forItem: $0, inSection: 0) }
}
}
}
dispatch_async(dispatch_get_main_queue()) {
self.currentIssueTableView.reloadData()
self.cellLoadingIndicator.stopAnimating()
self.cellLoadingIndicator.hidesWhenStopped = true
}
}
}
self.populatingCurrentIssue = false
}
}

Refactor cellForRowIndexPath in UITableView Swift

I have a rather long cellForRowAtIndexPath function. I am using parse as my backend and have a lot going on. I want to extract a lot of these conditions and put them in their own functions. Especially the PFUser query, but unfortunately I don't know whats the best way to go about it since I don't know how I can access the elements of each cell in those functions I want to write.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PostCells", forIndexPath: indexPath) as! NewsFeedTableCellTableViewCell
// Configure the cell...
// A drive is a post
let drive: PFObject = self.timelineData[indexPath.row] as PFObject
var driverId = drive.objectForKey("driver")!.objectId!
var currentUserObjectId = PFUser.currentUser()!.objectId
if(driverId != currentUserObjectId){
cell.requestButton.layer.borderWidth = 1
cell.requestButton.titleLabel!.font = UIFont.systemFontOfSize(11)
cell.requestButton.tintColor = UIColor.orangeColor()
cell.requestButton.layer.borderColor = UIColor.orangeColor().CGColor
cell.requestButton.setTitle("REQUEST", forState: UIControlState.Normal)
}
else {
cell.requestButton.layer.borderWidth = 1
cell.requestButton.titleLabel!.font = UIFont.systemFontOfSize(11)
cell.requestButton.tintColor = UIColor.grayColor()
cell.requestButton.layer.borderColor = UIColor.lightGrayColor().CGColor
cell.requestButton.setTitle("REQUEST", forState: UIControlState.Normal)
cell.requestButton.enabled = false
}
// Setting up the attributes of the cell for the news feed
cell.driveTitleTextField.text = drive.objectForKey("title") as! String
cell.wayTextField.text = drive.objectForKey("way") as! String
var departureDate = NSDate()
departureDate = drive.objectForKey("departureDate") as! NSDate
var dateFormat = NSDateFormatter()
dateFormat.dateFormat = "M/dd hh:mm a"
cell.departureDateTextField.text = dateFormat.stringFromDate(departureDate)
if((drive.objectForKey("way")!.isEqualToString("Two Way")))
{
var returnDate = NSDate()
returnDate = drive.objectForKey("returnDate") as! NSDate
cell.returningDateTextField.text = dateFormat.stringFromDate(returnDate)
}
else if((drive.objectForKey("way")!.isEqualToString("One Way")))
{
cell.returningDateTextField.enabled = false
cell.returningDateTextField.userInteractionEnabled = false
cell.returningDateTextField.hidden = true
cell.returningLabel.hidden = true
}
var seatNumber = NSNumber()
seatNumber = drive.objectForKey("seatNumber") as! NSInteger
var numberFormat = NSNumberFormatter()
numberFormat.stringFromNumber(seatNumber)
cell.seatNumberTextField.text = numberFormat.stringFromNumber(seatNumber)
// this is a PFUser query so we can get the users image and name and email from the User class
var findDrive = PFUser.query()
var objectId: AnyObject? = drive.objectForKey("driver")!.objectId!
findDrive?.whereKey("objectId", equalTo: objectId!)
findDrive?.findObjectsInBackgroundWithBlock{
(objects:[AnyObject]?, error:NSError?)->Void in
if (error == nil){
if let actualObjects = objects {
let possibleUser = (actualObjects as NSArray).lastObject as? PFUser
if let user = possibleUser {
cell.userProfileNameLabel.text = user["fullName"] as? String
cell.userEmailLabel.text = user["username"] as? String
//Profile Image
cell.profileImage.alpha = 0
if let profileImage = user["profilePicture"] as? PFFile {
profileImage.getDataInBackgroundWithBlock{
(imageData:NSData? , error:NSError?)-> Void in
if(error == nil) {
if imageData != nil{
let image:UIImage = UIImage (data: imageData!)!
cell.profileImage.image = image
}
}
}
}
UIView.animateWithDuration(0.5, animations: {
cell.driveTitleTextField.alpha = 1
cell.wayTextField.alpha = 1
cell.profileImage.alpha = 1
cell.userProfileNameLabel.alpha = 1
cell.userEmailLabel.alpha = 1
cell.seatNumberTextField.alpha = 1
cell.returningDateTextField.alpha = 1
cell.departureDateTextField.alpha = 1
})
}
}
}
}
return cell
}
EDIT 1
I came up with a way to refactor my code that I would like critiqued!
1. I extracted a lot of the cells configurations and put them into to functions, one for the button on the cell and the other for all the data from parse.
func configureDataTableViewCell(cell:NewsFeedTableCellTableViewCell, drive: PFObject)
{
cell.driveTitleTextField.text = drive.objectForKey("title") as! String
cell.wayTextField.text = drive.objectForKey("way") as! String
cell.userEmailLabel.text = drive.objectForKey("username") as? String
cell.userProfileNameLabel.text = drive.objectForKey("name") as? String
var departureDate = NSDate()
departureDate = drive.objectForKey("departureDate") as! NSDate
var dateFormat = NSDateFormatter()
dateFormat.dateFormat = "M/dd hh:mm a"
cell.departureDateTextField.text = dateFormat.stringFromDate(departureDate)
if((drive.objectForKey("way")!.isEqualToString("Two Way")))
{
var returnDate = NSDate()
returnDate = drive.objectForKey("returnDate") as! NSDate
cell.returningDateTextField.text = dateFormat.stringFromDate(returnDate)
}
else if((drive.objectForKey("way")!.isEqualToString("One Way")))
{
cell.returningDateTextField.enabled = false
cell.returningDateTextField.userInteractionEnabled = false
cell.returningDateTextField.hidden = true
cell.returningLabel.hidden = true
}
var seatNumber = NSNumber()
seatNumber = drive.objectForKey("seatNumber") as! NSInteger
var numberFormat = NSNumberFormatter()
numberFormat.stringFromNumber(seatNumber)
cell.seatNumberTextField.text = numberFormat.stringFromNumber(seatNumber)
}
func configureButtonTableViewCell(cell:NewsFeedTableCellTableViewCell, userID: String)
{
var currentUserObjectId = PFUser.currentUser()!.objectId
if(userID != currentUserObjectId){
cell.requestButton.layer.borderWidth = 1
cell.requestButton.titleLabel!.font = UIFont.systemFontOfSize(11)
cell.requestButton.tintColor = UIColor.orangeColor()
cell.requestButton.layer.borderColor = UIColor.orangeColor().CGColor
cell.requestButton.setTitle("REQUEST", forState: UIControlState.Normal)
println("orange")
}
else {
cell.requestButton.layer.borderWidth = 1
cell.requestButton.titleLabel!.font = UIFont.systemFontOfSize(11)
cell.requestButton.tintColor = UIColor.grayColor()
cell.requestButton.layer.borderColor = UIColor.lightGrayColor().CGColor
cell.requestButton.setTitle("REQUEST", forState: UIControlState.Normal)
cell.requestButton.enabled = false
println("gray")
}
}
2. I then passed in the functions from step 1 and into my cellForRowIndexPath
// A drive is a post
let drive: PFObject = self.timelineData[indexPath.row] as PFObject
var driverId : String = drive.objectForKey("driver")!.objectId!!
configureButtonTableViewCell(cell, userID: driverId)
configureDataTableViewCell(cell, drive: drive)
3. I stored all my PFUser data into my object when its saved instead of querying the user class. So I get the PFUser.currentUser() username, full name, and profile picture when they save a post.
My load data has been modified. I store all the profile pictures in there own array.
func loadData(){
var findItemData:PFQuery = PFQuery(className:"Posts")
findItemData.addDescendingOrder("createdAt")
findItemData.findObjectsInBackgroundWithBlock{
(objects:[AnyObject]? , error:NSError?) -> Void in
if error == nil
{
self.timelineData.removeAll(keepCapacity: false)
self.profilePictures.removeAll(keepCapacity: false)
self.timelineData = objects as! [PFObject]
for object in objects! {
self.profilePictures.append(object.objectForKey("profilePicture") as! PFFile)
}
self.newsFeedTableView.reloadData()
}
}
}
And finally, here is my updated cellForRowIndexPath
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("PostCells", forIndexPath: indexPath) as! NewsFeedTableCellTableViewCell
// Configure the cell...
// A drive is a post
let drive: PFObject = self.timelineData[indexPath.row] as PFObject
var driverId : String = drive.objectForKey("driver")!.objectId!!
configureButtonTableViewCell(cell, userID: driverId)
configureDataTableViewCell(cell, drive: drive)
println(PFUser.currentUser()?.objectForKey("username"))
if let profileImage = drive["profilePicture"] as? PFFile {
profileImage.getDataInBackgroundWithBlock{
(imageData:NSData? , error:NSError?)-> Void in
if(error == nil) {
if imageData != nil{
let image:UIImage = UIImage (data: imageData!)!
cell.profileImage.image = image
}
}
}
}
return cell
}
Let me know what you guys think, I want to do make my code much more readable, fast, and memory efficient.
You shouldn't be doing any heavy model stuff inside cellForRow.
What you're currently trying to do will greatly slow down your UI.
In most cases you will want your model objects setup, and ready to go before you even get to cellForRow.
This means performing your Parse queries somewhere like in viewDidLoad, keep those results in an array, and when it comes time to do so, apply them to your cells in cellForRow. This way, when a user scrolls, a new query won't be dispatched for every new cell that comes into view. It will already be available.
In addition to this, should you need to make any changes to these items once they have been fetched, you can do so, and have them remain unchanged even when the user is scrolling.
Refactor so you have some data type or group of instance variables to serve as a view model. Avoid making asynchronous calls that mutate the cell in cellForRowAtIndexPath. Instead have your data access method mutate or recreate the view model and at the end of your callback, dispatch_async to the main queue. Give it a closure that tells your table view to reloadData and whatever else you need to do for views to show the new data.
Here's a little pseudocode to describe what I mean:
func loadData() {
parseQueryWithCallback() { data in
self.viewModel = doWhateverTransformsAreNeeded(data)
dispatch_async(dispatch_get_main_queue(), self.tableView.reloadData)
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) {
let cell = dequeue(...)
cell.thingOne = self.viewModel.things[indexPath.row].thingOne
cell.thingTwo = self.viewModel.things[indexPath.row].thingTwo
return cell
}

Resources