I am trying to fetch data using an ID on the ViewController. I have two viewcontrollers, when I press the Cell (from ViewController 1), it has an ID and goes to ViewController 2 and fetches all the records that are assigned to the ID. For example, on ViewController 1, I have a UITableView and there are 20 cells. Each cells have an ID assigned to it dynamically from the database. When I press the cell, assuming I pressed 9th cell and its ID is 99, then it goes to the ViewController 2 and fetches all the records whose Foreign Key has ID 99.
Please find my code Below for ViewController 2:
import UIKit
import Alamofire
import SwiftyJSON
class CategoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSURLConnectionDelegate {
var tableData = Array<Category>()
var arrRes = [[String:AnyObject]]() //Array of dictionary
var category = [Category]()
var catTitle = ""
var id = ""
@IBOutlet weak var catTitleRec: UILabel!
@IBOutlet weak var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
catTitleRec.text = catTitle
loadCategories()
}
func loadCategories(){
let testhappyhour:Category = Category(tempName: "category.NAME", tempID: "category.id", tempgbcount: "TOTAL")
self.category.append(testhappyhour)
let postID = "id="+id
print("Response ID-is: \(postID)") // Able to get the ID here
Alamofire.request("http://www.URL.com.au/database/results.php").responseJSON
{ response in switch response.result {
case .success(let JSON):
let response = JSON as! NSArray
print("Response: \(response)")
for item in response { // loop through data items
let obj = item as! NSDictionary
let happyhour = Category(tempName:obj["category.NAME"] as! String, tempID:obj["category.id"] as! String, tempgbcount:obj["TOTAL"] as! String)
self.category.append(happyhour)
self.arrRes.append(obj as! [String : AnyObject]) // ADD THIS LINE
}
self.tableview.reloadData()
case .failure(let error):
print("Request failed with error: \(error)")
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableview.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return myarray.count
return arrRes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell") as! GroupCellTableViewCell
var dict = arrRes[indexPath.row]
cell.nametextlabel.text = dict["category.NAME"] as? String
cell.totaltextlabel?.text = dict["TOTAL"] as? String
return cell
}
}
Thanks for your time and effort :)