Sarah Malik Sarah Malik - 1 month ago 10
Swift Question

Swift: How can I get the records from the database according to the cell pressed

Is it possible to get the data from the external database when a UItableViewCell is pressed?

I managed to create a UItableView where I am displaying the data from the database. If I press a cell then all the data that are linked to it should be displayed. For eg. if I have 4 main categories in the database such as TOOLS, OTHERS, SECURITY, PETS and each of them has its sub-catecory and are linked with each other in the database. So if I click on Pets, it should filter out and only Show me CATS, DOGS, COWS, LIONS. When I run this SQL I am able to get the information but cant figure it this out on Swift.

UItableViewCell is in my FirstviewController and its the Main Category .
When I click here it goes to my destination VC and has the table again in here.enter image description here

DestViewController is the sub-category
enter image description here

My CategoryList_ViewController.swift

import Foundation
import UIKit
import WebKit

class CategoryList_ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

@IBAction func refresh(sender: AnyObject) {

get()
}
var values:NSArray = []

override func viewDidLoad() {
super.viewDidLoad()
get();
}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func get(){
let url = NSURL(string: "c:\deskstop\mobiletec\assignment\assignment2\cat.php")
let data = NSData(contentsOfURL: url!)
values = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
tableView.reloadData()
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count;
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CategoryList_TableViewCell
let maindata = values[indexPath.row]
cell.categoryLabel.text = maindata["NAME"] as? String
return cell;

}



override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "catView" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let value = values[indexPath.row]
let controller = segue.destinationViewController as! SubCatergory_ViewController
controller.cate_Id = value["id"] as! String
controller.catTitleRec = value["NAME"] as! String
}
}
}
}


my SubCatergory_ViewController.swift

import Foundation
import UIKit
import WebKit

class SubCatergory_ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var caID: UILabel!

@IBOutlet weak var catTitle_Label: UILabel!
@IBAction func refresh(sender: AnyObject) {

get()
}
var values:NSArray = []

var catTitleRec = ""
var cate_Id = ""

override func viewDidLoad() {
super.viewDidLoad()

catTitle_Label.text = catTitleRec
caID.text = cate_Id
get();
}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func get(){
let request = NSMutableURLRequest(URL: NSURL(string: "c:\deskstop\mobiletec\assignment\assignment2\subcat.php")!)
request.HTTPMethod = "GET"
let postString = "a=\(cate_Id)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

if error != nil {
print("error=\(error)")
return
}

print("response = \(response)")

let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count;
}



func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! subCateListTableViewCell
let maindata = values[indexPath.row]
cell.categoryLabel.text = maindata["NAME"] as? String
return cell;

}


}


and my subcat.php

<?php

$connection = mysql_connect(........);

$catefilter = $_GET['a'];
if(!$connection){
die('Connection Failed');
}
else{
$dbconnect = @mysql_select_db($database_UNIASSIGNMENT, $connection);

if(!$dbconnect){
die('Could not connect to Database');
}
else{
$query = 'SELECT category_group.group_id , category.NAME FROM category_group LEFT JOIN category ON category.id = category_group.category_id WHERE category_group.group_id =' . $catefilter ;
$resultset = mysql_query($query, $connection);

$records= array();

while($r = mysql_fetch_assoc($resultset)){
$records[] = $r;
}

echo json_encode($records);
}
}
?>


My first VC works fine but my second VC doesnot get the data

Thanks for your time :)

SK

Answer

To access the cell that has been pressed, you need to call the didSelectRowAtIndexPath function.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let value = values[indexPath.row]

    let vc = storyboard?.instantiateViewController(withIdentifier: "SubCatergory_ViewController") as! SubCatergory_ViewController

    vc.cate_Id = value["NAME"] as! String
    //self.navigationController?.pushViewController(vc, animated: true)
    self.present(vc, animated: true, completion: nil)
}

First you get the value out of your values Array on the indexPark.row. Then you instantiate your second viewController.

Then you set your String value of cate_Id to the desired String value of your item value. And then you just need to present the new viewController.

If you're using a UINavigationController and you want a "back" button, then you use: self.navigationController?.pushViewController(vc, animated: true)

If you just want to present the viewController, you use self.present(vc, animated: true, completion: nil)

Comment or uncomment whatever presentation method you prefer.

Comments