Table View is now shown in simülatör swift/xcode - swift

hello i am new to learning swift. I want to save data in database and show it in tableview. But even though I do everything, the tableview does not appear in the simulator. white screen appears. Any idea about the reason? I looked at the previous questions but couldn't find an answer.
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
#IBOutlet weak var tableView: UITableView!
//tanımlamalar
var nameArray = [String]()
var idArray = [UUID]()
override func viewDidLoad() {
super.viewDidLoad()
//tableview gösterme
tableView.delegate = self
tableView.dataSource = self
//add butonu ekleme
navigationController?.navigationBar.topItem?.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.add, target: self, action: #selector(addButtonClicked))
}
//verileri getirme
func getData() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
//getirme
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName : "Paintings")
fetchRequest.returnsObjectsAsFaults = false
do{
let results = try context.fetch(fetchRequest)
for result in results as! [NSManagedObject] {
if let name = result.value(forKey: "name") as? String{
self.nameArray.append(name)
}
if let id = result.value(forKey: "id") as? UUID{
self.idArray.append(id)
}
//yeni veri eklenirse tableviewı reload et
self.tableView.reloadData()
}
}catch{
print("error")
}
}
//add butonuna tıklanırsa ne olacak
#objc func addButtonClicked() {
performSegue(withIdentifier: "DetailsVC", sender: nil)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
var content = cell.defaultContentConfiguration()
content.text = nameArray[indexPath.row]
cell.contentConfiguration = content
return cell
}
}

Related

How to use NSPredicate to fetch request and populate second viewController with data when UItableView roll is pressed in first viewController

I'm coding a Note App in Swift 4. The root ViewController (NoteListViewController) gets populated when secondViewController (ComposeNoteViewController) Textfield and TextView are populated.
The problem is when I press a populated TableView cell, rather than fetch and display the content, it opens a fresh instance of theComposeNoteViewController.
import UIKit
import CoreData
class NoteListTableViewController: UITableViewController {
var noteListArray = [NoteListItem]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
loadNoteListItem()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return noteListArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NoteListItemCell", for: indexPath)
cell.textLabel?.text = noteListArray[indexPath.row].title
return cell
}
//MARK: - TABLEVIEW DELEGATE METHODS
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "goToComposeNote", sender: self)
tableView.deselectRow(at: indexPath, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! ComposeNoteViewController
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedNoteList = noteListArray[indexPath.row]
}
}
import UIKit
import CoreData
class ComposeNoteViewController: UIViewController {
var noteComposeItemsArray = [ComposeNote]()
var noteListArray = [NoteListItem]()
// let noteListController = NoteListTableViewController()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var selectedNoteList : NoteListItem? {
didSet {
loadComposeItem()
}
}
#IBOutlet weak var noteTextView: UITextView!
#IBOutlet weak var noteTextField: UITextField!
#IBAction func noteSavePressed(_ sender: UIBarButtonItem) {
let newNoteTitleItem = NoteListItem(context: context)
let newComposeNote = ComposeNote(context: context)
newNoteTitleItem.title = noteTextField.text!
newComposeNote.note = noteTextView.text!
newComposeNote.parentTitleNote = selectedNoteList
noteComposeItemsArray.append(newComposeNote)
noteListArray.append(newNoteTitleItem)
saveComposeItems()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func saveComposeItems() {
do {
try context.save()
}catch {
print("Error saving context \(error)")
}
reloadInputViews()
}
func loadComposeItem() {
let request : NSFetchRequest<ComposeNote> = ComposeNote.fetchRequest()
let predicate = NSPredicate(format: "parentTitleNote.title MATCHES %#", selectedNoteList!.title!)
request.predicate = predicate
do {
noteComposeItemsArray = try context.fetch(request)
}catch {
print("Can't load Items")
}
reloadInputViews()
}
}

TableViewCell.xib doesn't appear on tableview

Here is my code, it is supposed to display the users inside firebase database in customs tableviewcell.xib but when launching the app the tableview stays empty, I really don't know what's wrong in the code or what's missing, I think it is a really simple mistake but I can't figure it out.
Thanks in advance for those who will answer.
import UIKit
import Firebase
class UsersTableView: UIViewController, UITableViewDelegate, UITableViewDataSource {
// Outlets.
#IBOutlet weak var tableview: UITableView!
// Var.
var user = [User]()
override func viewDidLoad() {
super.viewDidLoad()
retrieveUsers()
// Do any additional setup after loading the view.
}
func retrieveUsers() {
let ref = Database.database().reference()
ref.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: { DataSnapshot in
let users = DataSnapshot.value as! [String: AnyObject]
self.user.removeAll()
for (_, value) in users{
//let uid = Auth.auth().currentUser!.uid
if let uid = value["userID"] as? String{
if uid != Auth.auth().currentUser!.uid {
let userToShow = User()
if let fullName = value["username"] as? String , let imagePath = value["photoURL"] as? String {
userToShow.username = fullName
userToShow.imagePath = imagePath
userToShow.userID = uid
self.user.append(userToShow)
}
}
}
}
self.tableview.reloadData()
})
ref.removeAllObservers()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableview.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserTableViewCell
cell.nameLabel.text = self.user[indexPath.row].username
cell.userID = self.user[indexPath.row].userID
cell.userImage.downloadImage(from: self.user[indexPath.row].imagePath!)
//checkFollowing(indexPath: indexPath)
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return user.count ?? 0
}
}
extension UIImageView{
func downloadImage(from imgURL: String!) {
let url = URLRequest(url: URL(string: imgURL)!)
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil{
print(error)
return
}
DispatchQueue.main.async {
self.image = UIImage(data: data!)
}
}
task.resume()
}
}
If you have not set delegate and datasource for your tableView in your storyboard do it programmatically:
override func viewDidLoad() {
super.viewDidLoad()
//Add these 2 lines, might be missed.
self.tableview.delegate = self
self.tableview.dataSource = self
retrieveUsers()
}
CheckList:
Set tableView Delegate and Datasource
self.tableview.delegate = self
self.tableview.dataSource = self
Registered custom tableViewCell?
let cellNIb = UINib.init(nibName:"Identifier_Name", bundle: nil)
register(cellNIb, forCellReuseIdentifier: identifier)
check the return count of func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
​
There are two things that you forgot:
Set dataSource of your table view as your controller. If you don't do it, your tableView won't want any data. So set it in controller's viewDidLoad
tableview.dataSource = self
If you created custom xib for your cell, don't forget to register your custom cell for table view (also you can do it in viewDidLoad)
tableview.register(UINib(nibName: "UserCardTableViewCell", bundle: nil), forCellReuseIdentifier: "UserCell")
If you need UITableViewDelegate methods like didSelectRowAt too, don't forget to set delegate of your table view as your controller too
tableview.delegate = self

UITableview cells aren't showing

UITableview is visible while the cells aren't.
This is for a food ordering app, and I'm trying to display the menu. I've tried everything, no error has shown, but the cells ain't visible
import UIKit
import FirebaseDatabase
import FirebaseCore
class MenuVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
var menu = [Food]()
var ref: DatabaseReference?
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
ref = Database.database().reference()
loadMenu()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menu.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "menuCell") as? MenuCell {
let foodItem = menu[indexPath.row]
cell.configCell(food: foodItem)
return cell
}else{
return UITableViewCell()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "popup", sender: menu[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let popupVC = segue.destination as? MenuPopUpVC {
if let foodItem = sender as? Food{
popupVC.config(food: foodItem)
}
}
}
func loadMenu() {
ref?.child("menu").observe(.value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let dict = snap.value as! [String: Any]
let foodName = dict["name"] as! String
print(foodName)
let foodPrice = dict["price"] as! String
let foodImg = dict["image"] as! String
let foodItem = Food(name: foodName, price: foodPrice, img: foodImg)
self.menu.append(foodItem)
}
})
}
}
import UIKit
import SDWebImage
class MenuCell: UITableViewCell {
#IBOutlet weak var PriceLbl: UILabel!
#IBOutlet weak var menuImg: UIImageView!
#IBOutlet weak var menuItemLbl: 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
}
func configCell(food : Food) {
let name = food.name ?? ""
menuItemLbl.text = name
let price = food.price ?? ""
PriceLbl.text = "$\(price)"
menuImg.sd_setImage(with: URL(string: food.img!)) {[weak self] (image, error, cachetype, url) in
if error == nil{
self?.menuImg.image = image
}
}
}
}
You don't reload data of your TableView, reload them after you append all foods to menu array (means after foreach loop)
ref?.child("menu").observe(.value, with: { (snapshot) in
for child in snapshot.children {
...
self.menu.append(foodItem)
}
self.tableView.reloadData()
})
You need to reload the tableView after you fill the array
self.menu.append(foodItem)
}
self.tableView.reloadData()
Also inside cellForRowAt , it's a good practice to
let cell = tableView.dequeueReusableCell(withIdentifier: "menuCell") as! MenuCell
without the misleading return UITableViewCell()

Search bar filtering wrong data

Disparately asking for your assistance
I am trying to filter Table View using search bar but the data I am getting is not in the correct position,
I tried several times to figure it out but without any chance, the result I am getting is only the first row does not matter which Room Number I am typing
I pasted the code below, your assistance is highly appreciated
final let urlString = "http://ccm-hotels.com/ccmandroid/api/getteams.php"
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var searchBar: UISearchBar!
#IBAction func BackToMenu(_ sender: UIBarButtonItem) {
let MainMenu = self.storyboard?.instantiateViewController(withIdentifier: "MainMenu") as! MainMenu
self.navigationController?.pushViewController(MainMenu, animated: true)
}
var openCaseRoomArray: [String] = []
var openCaseNameArray: [String] = []
var openCaseRoomArrayF: [String] = []
var inSearchMode = false
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
searchBar.delegate = self
searchBar.returnKeyType = UIReturnKeyType.done
openCaseRoomArrayF = openCaseRoomArray
let alertController = UIAlertController(title: nil, message: "Please wait\n\n", preferredStyle: .alert)
let spinnerIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5)
spinnerIndicator.color = UIColor.black
spinnerIndicator.startAnimating()
alertController.view.addSubview(spinnerIndicator)
self.present(alertController, animated: false, completion: nil)
let when = DispatchTime.now() + 5
DispatchQueue.main.asyncAfter(deadline: when){
// your code with delay
alertController.dismiss(animated: true, completion: nil);}
self.downloadJsonWithURL()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func downloadJsonWithURL() {
let url=URL(string:"http://ccm-hotels.com/ccmandroid/api/getteams.php")
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["CurrentOpenCases"] {
for index in 0...arrJSON.count-1 {
let aObject = arrJSON[index] as! [String : AnyObject]
if let Room = aObject["RoomNumber"] as? String {
openCaseRoomArray.append(Room)
}
if let Name = aObject["GuestName"] as? String {
openCaseNameArray.append(Name)
}
}
}
self.tableView.reloadData()
}
catch {
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if inSearchMode {
return openCaseRoomArrayF.count
}
return openCaseRoomArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
if inSearchMode {
cell.openCaseRoom.text = self.openCaseRoomArrayF[indexPath.row]
cell.openCaseName.text = self.openCaseNameArray[indexPath.row]
}else{
cell.openCaseRoom.text = self.openCaseRoomArray[indexPath.row]
cell.openCaseName.text = self.openCaseNameArray[indexPath.row]
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
vc.dopenCaseRoomString = openCaseRoomArray[indexPath.row]
vc.openCaseNameString = openCaseNameArray[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
inSearchMode = false
view.endEditing(true)
tableView.reloadData()
} else {
inSearchMode = true
openCaseRoomArrayF = openCaseRoomArray.filter({$0 == searchBar.text})
tableView.reloadData()
}
}
}
In your func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell method you are showing name from self.openCaseNameArray while you are updating your search result in self.openCaseRoomArrayF. When you are getting the api response you are assigning room and its corresponding name in your two arrays but when you are searching and updating your search result in self.openCaseRoomArrayF the index get changed. Now openCaseNameArray and openCaseRoomArray are in matched index but openCaseNameArray and openCaseRoomArrayF are not in same matched index. So you will not get the corresponding name in openCaseNameArray if you take room from openCaseRoomArrayF.
Try to make a Class (e.g Room) and store Room class object in a array. Search and show from that array. No need to maintain to array for this.

How do you change a fetchRequest to an Array to use in a UITableView

I am tying to put fetched data from coredata in a UITableView but I get this "EXC_BAD_INSTRUCTION" .
Using the let swiftBlogs Array works just fine, so can someone show my how to convert the fetch to an Array or is that not the correct way?
import UIKit
import CoreData
class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var scrollView: UIScrollView!
#IBOutlet var timeStampTextField: UITextField!
#IBOutlet var quickQuoteTextField: UITextField!
#IBOutlet var tableViewQuickQuote: UITableView!
let swiftBlogs = ["Ray Wenderlich", "NSHipster", "iOS Developer Tips", "Jameson Quave", "Natasha The Robot", "Coding Explorer", "That Thing In Swift", "Andrew Bancroft", "iAchieved.it", "Airspeed Velocity"]
var tableViewCellArray : Array<AnyObject> = []
var quickQuoteArray : Array<AnyObject> = []
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "QuickQuote" )
request.returnsObjectsAsFaults = false
tableViewCellArray = context.executeFetchRequest(request, error: nil)!
}
override func viewWillAppear(animated: Bool) {
quickQuoteTextField.text = ""
timeStampTextField.text = ""
}
#IBAction func clearButton(sender: AnyObject) {
quickQuoteTextField.text = ""
timeStampTextField.text = ""
}
#IBAction func addToQuickQuoteButton(sender: AnyObject) {
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let ent = NSEntityDescription.entityForName("QuickQuote", inManagedObjectContext: context)
var newQuickQuote = QuickQuote(entity: ent!, insertIntoManagedObjectContext: context)
newQuickQuote.quickQuote = quickQuoteTextField.text
context.save(nil)
}
#IBAction func timeStampButton(sender: AnyObject) {
timeStamp()
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let ent = NSEntityDescription.entityForName("Time", inManagedObjectContext: context)
var newTime = Time(entity: ent!, insertIntoManagedObjectContext: context)
newTime.time = timeStampTextField.text
newTime.quote = quickQuoteTextField.text
context.save(nil)
}
func timeStamp (){
timeStampTextField.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: NSDateFormatterStyle.FullStyle,
timeStyle: NSDateFormatterStyle.ShortStyle)
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return swiftBlogs.count // return quickQuoteArray.count
}
private let stampCellID: NSString = "cell" //This is the cell itself's identifier.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(stampCellID as String, forIndexPath: indexPath) as! UITableViewCell
var data: NSManagedObject = quickQuoteArray[indexPath.row] as! NSManagedObject
cell.textLabel?.text = data.valueForKey("quickQuote") as? String
// let row = indexPath.row
// cell.textLabel?.text = swiftBlogs[row]
return cell
}
/*
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context:NSManagedObjectContext = appDel.managedObjectContext!
if editingStyle == UITableViewCellEditingStyle.Delete {
let tv = tableView
context.deleteObject(quickQuoteArray.self[indexPath.row] as! NSManagedObject)
tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
}
context.save(nil)
}
*/
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
You're mixing up your arrays swiftBlogs and quickQuoteArray. Whether or not the table view tries to access an array element quickQuoteArray[indexpath.row] is dependent on if it thinks that index is populated, based on the result from numberOfRowsInSection. In the numberOfRowsInSection method, you are returning the count of swiftBlogs, which is always the 10 or so strings you hand-typed in. So before your request is ever even executed, or the view even has a chance to populate anything else, it's trying to show elements that aren't present in the array you're using in cellForRowAtIndexPath.
In short:
Always use the same array in cellForRowAtIndexPath as you are using in numberOfRowsInSection. Here, you've mixed two different arrays, quickQuoteArray and swiftBlogs.