Swift 3.0: Store array in UserDefaults for tableView - arrays

I'm attempting to store an array in UserDefaults yet have had no luck in finding a solution. I have a struct and func set up that work to store "name" and "description" in an array. The code is as follows...
struct task {
var name = "Untitled"
var description = "No description available"
}
var tasks = [task]()
func addTask(name: String, description: String) {
tasks.append(task(name: name, description: description))
}
What's the best way to store the data in UserDefaults and add the information to cell.textLabel?.text and cell.detailTextLabel?.text after a relaunch?

It is Swift convention to name your structs starting with an uppercase letter. You need to make a class, make it NSCoding compliant and use KeyedArchiever to save the object data
class Task: NSObject, NSCoding {
let name: String
let desc: String
required init(name: String, desc: String) {
self.name = name
self.desc = desc
}
func encode(with coder: NSCoder) {
coder.encode(name, forKey: "name")
coder.encode(desc, forKey: "desc")
}
required init(coder decoder: NSCoder) {
self.name = decoder.decodeObject(forKey: "name") as? String ?? ""
self.desc = decoder.decodeObject(forKey: "desc") as? String ?? ""
}
}
Testing
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var nameField: UITextField!
#IBOutlet weak var descField: UITextField!
#IBOutlet weak var tableView: UITableView!
var tasks: [Task] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
if let data = UserDefaults.standard.data(forKey: "tasks") {
tasks = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Task] ?? []
tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func addTask(_ sender: UIButton) {
guard let name = nameField.text, let desc = descField.text else { return }
tasks.append(Task(name: name, desc: desc))
UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: tasks) , forKey: "tasks")
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellID")!
cell.textLabel?.text = tasks[indexPath.row].name + " - " + tasks[indexPath.row].desc
return cell
}
}

Related

Im having issues to show the array data after I decode it from JSON. How do I show the array to table view using delegate

I already have the array that is printed on the console after I decode it from JSON data. However, the table delegate are not working.
I tried using static array that is created on viewController and its working , but when I use the JSON data it wont work anymore. here is my table view protocols below.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return placeModel.indexCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = UITableViewCell(style: .default, reuseIdentifier: "restoCell")
let cell = tableView.dequeueReusableCell(withIdentifier: "restoCell", for: indexPath)
let array = placeModel.name[indexPath.row]
cell.textLabel?.text = String (array)
return cell
}
Here is whats on my ViewController , take note that the PlacesModel is at another swift file. the DispatchQueue.main.async is placed at didUpdateRestoLocation function. i tried place the delegate but still not working
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var placesManager = PlacesManager()
var placesClient = GMSPlacesClient()
var placeModel = PlacesModel(name: [], placesID: [], indexCount: 0)
#IBOutlet weak var cityText: UILabel!
#IBOutlet weak var kahitSaan: UILabel!
#IBOutlet weak var tableViewCafe: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//ask location authorization
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
placesManager.delegate = self
locationManager.delegate = self
tableViewCafe.delegate = self
tableViewCafe.dataSource = self
}
//MARK: - gps button
#IBAction func button(_ sender: Any) {
locationManager.startUpdatingLocation()
}
}
//MARK: - location manager delegate
extension ViewController {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
let lat = location.coordinate.latitude
let lon = location.coordinate.longitude
placesManager.fetchCafes( latitude: lat , longitude: lon)
}
locationManager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}
//MARK: - PLACESMANAGER - DELEGATE
extension ViewController : PlacesManagerDelegate {
func didUpdateRestoLocation(_ placeManager: PlacesManager, placesModel: PlacesModel) {
DispatchQueue.main.async {
self.kahitSaan.text = "\(placesModel.name[0])"
self.tableViewCafe.reloadData()
}
}
func didFailWithErrorProblem(error: Error) {
print(error)
}
//MARK: - table view populate
extension ViewController : UITableViewDelegate , UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//indexCount is the number of index of array from the data.
return placeModel.indexCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = UITableViewCell(style: .default, reuseIdentifier: "restoCell")
let cell = tableView.dequeueReusableCell(withIdentifier: "restoCell", for: indexPath)
let array = placeModel.name[indexPath.row]
cell.textLabel?.text = String (array)
return cell
}
}
my swift file PlaceModel.swift is at below. this is where the json data is placed after is was parsed.
struct PlacesModel {
let name : [String]
let placesID : [String]
let indexCount : Int
}
> here is the array of restaurant names
`["BJ\'s Restaurant & Brewhouse", "Fish\'s Wild", "Starbucks", "Pho Hoa Noodle Soup - Homestead", "Yayoi Cupertino", "Chipotle Mexican Grill", "Gochi Cupertino", "212 New York Pizza", "Oakmont Sandwiches", "Via Mia Pizza", "Mr. Ma’s Kitchen", "Bento Corner", "Duan Chun Zhen Noodle House", "Lei Garden", "Parkview Kitchen & Spirits", "Homestead Bowl & The X Bar", "Lee\'s Sandwiches", "TLT & Grill Soup", "Taiwan Porridge", "Taste Good Beijing Cuisine- Cupertino"]`

How Create Global Array and save Values in Two TableViews in Swift

Here i am creating Global array and appending values to it, which i need to save in two different viewcontrollers tableview
Global array and appending values and sending to two view controllers code:
var addressArray = [String]()
class NewZoomAddressViewController: UIViewController {
weak var delegate: DataEnteredDelegate? = nil
//var addressArray = [String]()
var zipName: String?
var localityName: String?
var sublocalityName: String?
var streetNumber: String?
var streetName: String?
#IBOutlet weak var mapView: MKMapView!
#IBOutlet weak var addressLabel: UILabel!
var viewController: UIViewController?
#IBAction func confirmBtn(_ sender: Any) {
for controller in navigationController?.viewControllers ?? [] {
if let listController = controller as? ProfileViewController {
let string = "\(streetNumber ?? "") \(streetName ?? "") \(sublocalityName ?? "") \(zipName ?? "") \(localityName ?? "")"
saveaddAddressService()
listController.addressArray.append(string)
navigationController?.popToViewController(controller, animated: true)
return
}
else if let listController = controller as? Add_EditAddressViewController {
let string = "\(sublocalityName ?? "") \(zipName ?? "") \(localityName ?? "")"
listController.addressArray.append(string)
saveaddAddressService()
navigationController?.popToViewController(controller, animated: true)
return
}
}
}
func saveaddAddressService(){
let parameters: [String: Any] = [
"pincode": zipName,
"city": localityName,
"streetName": sublocalityName,
"colony": "",
]
//some JSON code.....
let httpResponse = response as? HTTPURLResponse
if httpResponse!.statusCode == 200 {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String: Any]
self.addAddrsID = jsonObject["addressId"] as! String
UserDefaults.standard.set(self.addAddrsID, forKey: "addAddress")
} catch { print(error.localizedDescription) }
}
})
dataTask.resume()
}
Saving array in first view controller view controllers: here i am getting each time with new address the model address also coming, i dont know why?
class ProfileViewController: UIViewController {
var userModel : ProfileModel?
var addressArray = [String]()
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.navigationBar.isHidden=true
getUserProfile()
}
func getUserProfile() {
let httpResponse = response as? HTTPURLResponse
if httpResponse!.statusCode == 200 {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String :AnyObject]
self.userModel = ProfileModel.init(fromDictionary: jsonObject)
if (self.userModel?.userId) != nil {
DispatchQueue.main.async {
self.updateUserDetails()
self.addressTableview.reloadData()
}
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if userModel?.userAddresses != nil{
return userModel?.userAddresses.count ?? 0
}
else{
return addressArray.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: AddresCell = tableView.dequeueReusableCell(withIdentifier: "AddresCell") as! AddresCell
let addr = userModel?.userAddresses![indexPath.row]
if addr?.addressId != nil{
let street = addr?.streetName
let colony = addr?.colony
let city = addr?.city
let pincode = addr?.pincode
cell.address.text = street! + "," + colony! + "," + city! + "," + pincode!
}
else{
cell.address.text = addressArray[indexPath.row]
print("added address in profilr \(cell.address.text)")
}
return cell
}
saving global array in second view controller: here array values are coming, but if i go from this view controller to other view controller the array values gone(not coming.. showing empty.. not saving)
class Add_EditAddressViewController: UIViewController,DataEnteredDelegate {
#IBOutlet weak var addeditTableview: UITableView!
var addressArray = [String]()
override func viewWillAppear(_ animated: Bool) {
addeditTableview.reloadData()
}
}
extension Add_EditAddressViewController : UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return addressArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "EditAddressTableViewCell", for: indexPath) as! EditAddressTableViewCell
cell.editButton.addTarget(self, action: #selector(editbuttonClicked(sender:)), for: .touchUpInside)
cell.nameHeader.text = "Other"
cell.addressLabel.text = addressArray[indexPath.row]//"\(city) \(pincode) \(locality)"
}
return cell
}
you can create a singleton class to manage your global array like below GlobalArrayManager class:
import Foundation
class GlobalArrayManager{
static let shared = GlobalArrayManager()
var globalArray : [Int] = []
private init(){}
func getArray()->[Int]{
return globalArray
}
func addDataInArray(data : Int){
globalArray.append(data)
}
}
In first ViewController add data and print:
GlobalArrayManager.shared.addDataInArray(data: 100)
print("array values : ",GlobalArrayManager.shared.getArray())
Output In first ViewController:
array values : [100]
In second ViewController add data and print:
GlobalArrayManager.shared.addDataInArray(data: 200)
print("array values : ",GlobalArrayManager.shared.getArray())
Output In Second ViewController:
array values : [100, 200]
you can add more functionalities in your manager class

UICollectionView in UITableView - I want to show data in CollectionVewCell

I want to show data in UICollectionView. Which is coming from UITableView cell. My main concern is this. I am passing a key catgID from cellForRowAt in another API and getting data from it. But data is not coming proper way.
I am passing catgID from cellForRowAt and getting in another API which will show the list of data for UICollectionViewCells. Now data is coming but not in proper way.
This is my UITableView class for tableview index.
import UIKit
import Reachability
import Alamofire
var arrayMenuProducts = [structMenuProducts]()
struct structMenuProducts {
var id:Int
var product_name:String
var category:String
var product_image:String
var price:String
var unit_price:Double
var addons:NSArray
}
class MenuVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
var reachability = Reachability()!
#IBOutlet weak var tableview: UITableView!
var arrayMenuCat = [structMenuCat]()
struct structMenuCat{
var id:Int
var category_name:String
}
override func viewDidLoad() {
super.viewDidLoad()
menuVegAPI()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayMenuCat.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
catgID = arrayMenuCat[indexPath.row].id
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1") as! MenuTableCell
cell.lblCategoryTitle.text = arrayMenuCat[indexPath.row].category_name
cell.collectionviewOne.reloadData()
// let catid = arrayMenuCat[indexPath.row].id
// print(catid)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 216
}
func menuVegAPI()
{
if (reachability.connection == .wifi) || (reachability.connection == .cellular)
{
arrayMenuCat.removeAll()
SwiftLoader.show(animated: true)
let url = BaseUrl + ViewController.sharedInstance.menuCategory
print(url)
Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default).responseJSON { response in
SwiftLoader.hide()
switch response.result {
case .success:
let json = response.result.value
print(json)
let code = (json as AnyObject).object(forKey: "code") as! Int
print(code)
if code == 200
{
let data = (json as AnyObject).object(forKey: "data") as? NSArray
for alldata in data!
{
let id = (alldata as AnyObject).object(forKey: "id") as! Int
let category_name = (alldata as AnyObject).object(forKey: "category_name") as! String
let arr = structMenuCat(id: id, category_name: category_name)
self.arrayMenuCat.append(arr)
// self.menuProductsAPI(categoryid: id)
}
self.tableview.reloadData()
}
else
{
}
case .failure:
print("error")
}
}
}
else
{
alert(title: "", message: "Please Check Your Internet Connection")
}
}
}
This is my TableViewCell type class. In this class I am show data on CollectionView. Its code is here
import UIKit
import Alamofire
import Reachability
var catgID : Int!
var collectionreload : UICollectionView?
class MenuTableCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
var reachability = Reachability()!
#IBOutlet weak var lblCategoryTitle: UILabel!
#IBOutlet weak var collectionviewOne: UICollectionView!
var arrayMenuProducts = [structMenuProducts]()
struct structMenuProducts {
var id:Int
var product_name:String
var category:String
var product_image:String
var price:String
var unit_price:Double
var addons:NSArray
}
override func awakeFromNib() {
super.awakeFromNib()
collectionreload = self.collectionviewOne
print(arrayMenuProducts)
print(catgID ?? 0)
menuProductsAPI(categoryid: catgID!)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayMenuProducts.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellRID", for: indexPath) as! MenuCollectionViewCell
let abc = arrayMenuProducts[indexPath.row].product_name
print(abc)
// if catgID == Int(arrayMenuProducts[indexPath.row].category)
// {
cell.lblTitleForVeg.text = arrayMenuProducts[indexPath.row].product_name
cell.lblForPriceVeg.text = "$\(arrayMenuProducts[indexPath.row].unit_price)"
}
func menuProductsAPI(categoryid:Int)
{
if (reachability.connection == .wifi) || (reachability.connection == .cellular)
{
SwiftLoader.show(animated: true)
arrayMenuProducts.removeAll()
let url = BaseUrl + ViewController.sharedInstance.menuProducts + "categoryid=\(categoryid)"
print(url)
Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success:
let json = response.result.value
print(json)
// self.tableview.reloadData()
let code = (json as AnyObject).object(forKey: "code") as! Int
print(code)
if code == 200
{
let data = (json as AnyObject).object(forKey: "data") as? NSArray
DispatchQueue.main.async {
for alldata in data!
{
let id = (alldata as AnyObject).object(forKey: "id") as! Int
let product_name = (alldata as AnyObject).object(forKey: "product_name") as! String
let category = (alldata as AnyObject).object(forKey: "category") as! String
let product_image = (alldata as AnyObject).object(forKey: "product_image") as! String
let price = (alldata as AnyObject).object(forKey: "price") as! String
let unit_price = (alldata as AnyObject).object(forKey: "unit_price") as! Double
let addons = (alldata as AnyObject).object(forKey: "addons") as? NSArray
let arr = structMenuProducts(id: id, product_name: product_name, category: category, product_image: product_image, price: price, unit_price: unit_price, addons: addons!)
self.arrayMenuProducts.append(arr)
}
self.collectionviewOne.reloadData()
SwiftLoader.hide()
}
}
else
{
}
case .failure:
print("error")
}
}
}
else
{
// alert(title: "", message: "Please Check Your Internet Connection")
}
}
}
I want to show data coming in CollectionView in a proper formate. If Tableview index == 0 and Category id is coming 10 then. Category id 10 will first then one by one in a sequence I want to pass category id. In my case Category id is not coming in a queue.
Update the tableview datasource method as
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1") as! MenuTableCell
cell.lblCategoryTitle.text = arrayMenuCat[indexPath.row].category_name
cell.menuProductsAPI(categoryid: arrayMenuCat[indexPath.row].id)
return cell
}
And remove menuProductsAPI(categoryid: catgID!) from awakeFromNib method

TableView does not populate JSON array in Swift 3

I've read a lot of related questions here, but am still struggling with populating my tableview. I get the result from the print(firstname) and print(lastname) in the console. But nothing appears in the tableview.
The Table view has a Prototype cell with identifier BasicCell.
Any idea why the table is not populating?
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var listTableView: UITableView!
let URL_GET_PERSONAGE = "http://somesite.net/somescript.php"
var firstnames: [String] = []
var lastnames: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: URL_GET_PERSONAGE)
do{
let allContactsData = try Data(contentsOf: url!)
let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
if let arrJSON = allContacts["teams"] as? NSArray{
for index in 0..<arrJSON.count{
let aObject = arrJSON[index] as? [String : AnyObject]
firstnames.append(aObject?["fname"] as! String)
lastnames.append(aObject?["lname"] as! String)
}
print(firstnames)
print(lastnames)
listTableView.reloadData()
}
}
catch {
}
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.firstnames.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: UITableViewCell! = self.listTableView.dequeueReusableCell(withIdentifier: "BasicCell", for: indexPath as IndexPath) as UITableViewCell!
cell.textLabel?.text = self.firstnames[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

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
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.

Resources