I have a page with a TableView that fills each cell with a hardcoded UILabel of some text. I would like it to fill up with UILabels from a JSON that I get online.
Storyboard:
The code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var objects: NSMutableArray! = NSMutableArray()
override func viewDidLoad(){
super.viewDidLoad()
self.objects.add("iPhone")
self.objects.add("Apple Watch")
self.objects.add("Mac")
self.objects.add("Test")
self.tableView.reloadData()
}
override func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(_ tableView: UITableView) -> Int{
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return self.objects.count
}
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell{
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.titleLabel.text = self.objects.object(at: (indexPath as NSIndexPath).row) as? String
//cell.logButton.tag = (indexPath as NSIndexPath).row;
//cell.logButton.addTarget(self, action: #selector(ViewController.logAction(_:)), for: .touchUpInside)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath){
self.performSegue(withIdentifier: "showView", sender: self)
}
#IBAction func logAction(_ sender: UIButton) {
let titleString = self.objects[sender.tag] as? String
let firstActivityItem = "\(titleString!)"
let activityViewController : UIActivityViewController = UIActivityViewController(activityItems: [firstActivityItem], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if (segue.identifier == "showView"){
let upcoming: NewViewController = segue.destination as! NewViewController
let indexPath = self.tableView.indexPathForSelectedRow!
let titleString = self.objects.object(at: indexPath.row) as? String
upcoming.titleString = titleString
self.tableView.deselectRow(at: indexPath, animated: true)
}
}
}
Once in simulator and I open up the page, the TableView will have four cells with the "Label" changing to whatever was adding to the objects array, which in this case is iPhone, Apple Watch, Mac, and Test. Rather than having those hardcoded, I would like to have the items loaded from a JSON file.
I have the same thing done with a PickerView, but I am struggling to figure out how to do it with this. Here is how it was done with my PickerView if it helps:
Alamofire.request("example.com/file.json").responseJSON{ response in
if let JSON = response.result.value as? [String:AnyObject] {
self.mypickerview.delegate = self
self.mypickerview.dataSource = self
let result = JSON.values.flatMap({ String(describing: $0) })
self.pickerData.append(contentsOf: result)
self.pickerData.sort()
self.verbose.text = "Content saved!"
self.mypickerview.reloadAllComponents()
self.mypickerview.delegate = self;
self.verbose.text = "Finished Loading!"
}
}
The JSON file:
{"One":"Mac","Two":"Apple iPhone","Three":"Test"}
1.On viewDidLoad fire the webService.
2.On Webservice completion handler ,retreive the label values and assign to objects.
3.Reload tableview.
your JSON should look like this:
{
"titles": [
"mac",
"iphone",
"test"
]
}
and you will do something like cell.titleLabel.text = [[yourJSON valueForKey:#"titles"] objectAtIndex:indexPath.row];
(this is Obj-C version, but ofc it can be done also in swift)
Related
I have two viewControllers one called programlist that displays the list of tiles and populates a a suitable view.
the second viewController inputs the data. Issues implementing the callback due to an error in the prepareForsegue function. Getting the error "Instance member 'callback' cannot be used on type 'addWorkout'"
viewController 1 aka Programlist:
import UIKit
struct Item: Codable {
var title: String
var others: [String]
}
class ProgramList: UIViewController, UITableViewDataSource, UITableViewDelegate{
var Programs = [Item]()
#IBOutlet weak var programTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
load()
}
//saving current state of programs array
func save() {
guard let data = try? JSONEncoder().encode(Programs) else { return }
UserDefaults.standard.set(data, forKey: "notes")
}
//loading saved program array
func load() {
guard let loadedData = UserDefaults.standard.data(forKey: "notes") else { return }
do {
Programs = try JSONDecoder().decode([Item].self, from: loadedData)
programTableView.reloadData()
} catch { print(error) }
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Programs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.programTitle.text = Programs[indexPath.row].title
return cell
}
//Removing Item by swipping left & saving this newly established array
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
Programs.remove(at: indexPath.row)
programTableView.reloadData()
save()
}
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toAddPage"{
workoutController.callback = { [weak self] string in
let entered = Item(title: string, others: ["hi"])
self?.programs.append(entered)
let indexPath = IndexPath(row: self?.programs.count - 1, section: 0)
self?.tableView.insertRows(at: [indexPath], with: .automatic)
self?.save()
}
}
}
}
}
}
viewController 2 aka addWorkout:
import UIKit
class addWorkout: UIViewController {
#IBOutlet weak var workoutTitle: UITextField!
var callback : ((String) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func saveWorkoutTitle(_ sender: Any) {
if !workoutTitle.text!.isEmpty {
callback?(workoutTitle.text!)
}
}
}
The main mistake is you are trying to save an array of Item – which is not supported anyway – to UserDefaults and read an array of String. That's a clear type mismatch.
To be able to save an array of a custom struct to UserDefaults adopt Codable to save the struct as JSON.
struct Item : Codable {
var title: String
var others: [String]
}
Further it's a very bad practice to declare a data source array outside of any class.
This is the ProgramList class with adjusted load and save methods and the data source array inside the class. The method viewDidAppear is not needed.
class ProgramList: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var programTableView: UITableView!
var programs = [Item]()
override func viewDidLoad() {
super.viewDidLoad()
load()
}
//saving current state of programs array
func save() {
guard let data = try? JSONEncoder().encode(programs) else { return }
UserDefaults.standard.set(data, forKey: "notes")
}
//loading saved program array
func load() {
guard let loadedData = UserDefaults.standard.data(forKey: "notes") else { return }
do {
programs = try JSONDecoder().decode([Item].self, from: loadedData)
programTableView.reloadData()
} catch { print(error) }
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return programs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.programTitle.text = programs[indexPath.row].title
return cell
}
//Removing Item by swipping left & saving this newly established array
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
programs.remove(at: indexPath.row)
programTableView.deleteRows(at: [indexPath], with: .automatic)
save()
}
}
}
To share data between controllers use a closure as callback and pass the string
class AddWorkout: UIViewController {
#IBOutlet weak var workoutTitle: UITextField!
var callback : ((String) -> Void)?
#IBAction func saveWorkoutTitle(_ sender: Any) {
if !workoutTitle.text!.isEmpty {
callback?(workoutTitle.text!)
}
}
}
Back in ProgramList controller assign a closure to the callback property in prepareForSegue (or right before presenting the controller)
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toAddPage" {
let workoutController = segue.destination as! AddWorkout
workoutController.callback = { string in
let entered = Item(title: string, others: ["hi"])
self.programs.append(entered)
let indexPath = IndexPath(row: self.programs.count - 1, section: 0)
self.tableView.insertRows(at: [indexPath], with: .automatic)
self.save()
}
}
}
This has stumped me and Ive tried a few ways of doing of tutorials and on stack answers but its still not building.
So basically:
Im getting core data and then placing that into an array. (works fine)
After that Im just display first and last name in the cells (works fine)
User taps on cell to see athleteDetalView
I have placed a few print statements to see where its going wrong.
Thanks In advance for your input.
import UIKit
import CoreData
class athleteViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//labels
#IBOutlet weak var athleteLabel: UILabel!
//buttons
#IBOutlet weak var athleteCreate: UIBarButtonItem!
#IBOutlet weak var athleteTableView: UITableView!
var athleteArray:[Athlete] = []
var myIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
athleteTableView.delegate = self
athleteTableView.dataSource = self
self.fetchData()
self.athleteTableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return athleteArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "athleteName", for: indexPath)
let name = athleteArray[indexPath.row]
cell.textLabel!.text = name.firstName! + " " + name.lastName!
let athleteName = name.firstName!
let lastName = name.lastName!
let age = name.age!
let sport = name.sport!
let email = name.email!
print(athleteName)
print(lastName)
print(age)
print(sport)
print(email)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myIndex = indexPath.row
let currentCell
//let storyboard = UIStoryboard(name: "Main", bundle: nil)
//let destination = storyboard.instantiateViewController(withIdentifier: "athleteDetailsViewController") as! athleteDetailsViewController
//let athName = athleteArray[myIndex]
//testdata
//test data
performSegue(withIdentifier: "athleteDetailsSegue", sender: self)
//self.navigationController?.pushViewController(destination, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "athleteDetailsSegue") {
var destination = segue.destination as! athleteDetailsViewController
destination.firstNameString = athleteName
destination.lastNameString = lastName
destination.ageString = age
destination.sportString = sport
destination.emailString = email
//destination.getImage = name.image
}
}
func fetchData(){
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do{
athleteArray = try context.fetch(Athlete.fetchRequest())
}
catch{
print(error)
}
}
The variables that you are setting in tableView:cellForRowAt:indexPath: are local variables and are not available in the function prepareForSegue:. Try to declaring the variables at the top as properties of the class.
I am trying to create a custom table view but stumble upon every code. As of right now, I have this below. It's messy and probably wrong but could someone help?
Also, I keep getting an error code
unexpectedly found nil while unwrapping optional value
import UIKit
class tableOutlineViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var names = ["Max", "Bill", "Reagan", "Mikayla", "Jessie", "Sierra", "Jeff", "Erik", "Landon"]
var numbers = ["35", "33", "29", "27", "25", "23", "19", "15", "11"]
var photo = [UIImage(named: "Person1"), UIImage(named: "Person2"), UIImage(named: "Groceries"), UIImage(named: "Person3"), UIImage(named: "Person4"), UIImage(named: "Person5"), UIImage(named: "Person6"), UIImage(named: "Person7")]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
cell.images.image = photo[indexPath.row]
cell.name.text = names[indexPath.row]
cell.number.text = numbers[indexPath.row]
return cell
}
}
The error is at the following line because it's unable to force unwrap CustomCell:
let cell = self.tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
As you may be using Nib for your custom cell, you should firstly get it registered in viewDidLoad.
let nib = UINib(nibName: YOUR_CUSTOM_CELL_NIB_NAME, bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "CustomCell")
Seems like you forgot to define identifier(CustomCell) inside attribute inspector of your Xib file of custom cell. So you when you are doing force unwrapped you are getting nil. Also avoid doing force unwrapped to avoid the crash. Have refactored the code :-
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = self.tableView.dequeueReusableCell(withIdentifier: "CustomCell") as? CustomCell else {return UITableViewCell()}
cell.images.image = photo[indexPath.row]
cell.name.text = names[indexPath.row]
cell.number.text = numbers[indexPath.row]
return cell
}
Firs of all please do not populate your tableview with multiple arrays. These arrays can easily go out of sync and can cause a crash. You should ideally create a struct class having name, age and photo as its elements. Then you should have an array of struct class to populate your table view.
Here as well in you name array you have 9 elements whereas your image array has 8 elements. This is causing your app to crash as cell for row at indexpath method is not able to find the 9th image.
cell.images.image = photo[indexPath.row]
So I took everyone's advice and when I run the code below, I get zero errors. But in the simulator, it shows an empty tableView and the image I placed above the tableView is another image from another View Controller. I don't know if it's the code or something else.
let nib = UINib(nibName: "CustomCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "Cell")
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell") as? CustomCell else {return UITableViewCell()}
cell.images.image = photo[indexPath.row]
cell.name.text = names[indexPath.row]
cell.numbers.text = numbers[indexPath.row]
return cell
and my CustomCell
import UIKit
class CustomCell: UITableViewCell {
#IBOutlet weak var images: UIImageView!
#IBOutlet weak var name: UILabel!
#IBOutlet weak var numbers: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
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.
I have two tableView running in my project.I have successfully passed data from my first tableView to second tableView controller using segue.I am trying to save the data which i passed to secondViewController using NSUserDefaults.My partial code below....
First VC:
var tableView: UITableView!
var DataArray = ["Bus","Helicopter","Truck","Boat","Bicycle","Motorcycle","Plane","Train","Car","S cooter","Caravan"]
var sendSelectedData = NSString()
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath) as UITableViewCell!
// print(indexPath)
// print(currentCell)
sendSelectedData = (currentCell!.textLabel?.text)! as String as NSString
performSegue(withIdentifier: "ShowDetails", sender: indexPath)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let selectedIndex = sender as! NSIndexPath
let currentCell = tableView.cellForRow(at: selectedIndex as IndexPath)!
self.sendSelectedData = (currentCell.textLabel?.text)! as String as NSString
if segue.identifier == "ShowDetails" {
let viewController = segue.destination as! SecondController
viewController.newItem = (self.sendSelectedData as String)
}
}
Second VC:
var NewArray = [""]
var newItem: String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NewArray.insert(newItem, at: Array.count)
self.tableView?.beginUpdates()
// NewArray.append(newItem)
let defaults = UserDefaults.standard
defaults.object(forKey: "NewArray")
self.tableView?.endUpdates()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
cell.textLabel?.text = NewArray[(indexPath as NSIndexPath).row] as String
return cell
}
func insertRowsAtIndexPaths(indexPaths: [AnyObject], withRowAnimation animation: UITableViewRowAnimation) {
}
func reloadRowsAtIndexPaths(indexPaths: [AnyObject], withRowAnimation animation: UITableViewRowAnimation) {
}
I am following https://grokswift.com/uitableview-updates/ article to achieve the function....
Thanks in Advance.
In AppDelegate applicationDidFinishLaunching register an empty array as default value for the key "NewArray".
let defaultValues = ["NewArray": [String]()]
UserDefaults.standard.register(defaults: defaultValues)
In Second VC define newArray (variable names are supposed to start with a lowercase letter) also as empty String array
var newArray = [String]()
In viewDidLoad retrieve the array from user defaults, append the new item, save the array back to user defaults and reload the table view
override func viewDidLoad() {
super.viewDidLoad()
let defaults = UserDefaults.standard
newArray = defaults.array(forKey: "NewArray") as! [String]
newArray.append(newItem)
defaults.set(newArray, forKey: "NewArray")
self.tableView?.reloadData()
}
beginUpdates(), endUpdates() and insertRowsAtIndexPath / reloadRowsAtIndexPaths are not needed at all.