Reputation: 70
I am saving 2 tables information using core data one is Customer and other is Booked Tickets. one customer can book many tickets. I want to fetch this related data and populate in table view .I am getting all ticket data but I want ticket information of particular user. for example users.ticket.passangerName. But I am getting nil here.
import UIKit
import CoreData
class BookHistoryVC: UIViewController {
@IBOutlet weak var tableView: UITableView!
var tickets: [BookedTickets]? {
didSet{
tableView.reloadData()
}
}
var users: [Customer] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view.
self.fetch { (complete) in
if complete {
guard let tickets = tickets else {
return
}
if (tickets.count) >= 1 {
//tableView.isHidden = false
print(tickets as Any)
} else {
return
}
} else {
//tableView.isHidden = true
}
}//Fetch Complete
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func fetch(completion: (_ complete : Bool) -> ()) {
guard let managedContext = appDelegate?.persistentContainer.viewContext else { return }
let fetchRequest1 = NSFetchRequest<NSFetchRequestResult>(entityName: "Customer")
let fetchRequest2 = NSFetchRequest<NSFetchRequestResult>(entityName: "BookedTickets")
do {
users = try managedContext.fetch(fetchRequest1) as! [Customer]
tickets = try ((managedContext.fetch(fetchRequest2) as? [BookedTickets]))
print("Succesfully Fetched")
tableView.reloadData()
completion(true)
} catch {
debugPrint("Could Not Fetch:\(error.localizedDescription)")
completion(false)
}
}
}
extension BookHistoryVC: UITableViewDelegate, UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
guard let tickets = tickets else {
return 0
}
return tickets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "BookHistoryVCCell", for: indexPath) as? BookHistoryVCCell else { return UITableViewCell()}
guard let tickets = tickets else {
return UITableViewCell()
}
let ticket = tickets[indexPath.row]
cell.configureCell(ticket: ticket)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 400
}
}
In cell ...
import UIKit
class BookHistoryVCCell: UITableViewCell {
@IBOutlet weak var bookerNameLabel: UILabel!
@IBOutlet weak var ageLabel: UILabel!
@IBOutlet weak var passangerNameLabel: UILabel!
@IBOutlet weak var ticketNumberLabel: UILabel!
@IBOutlet weak var fromLabel: UILabel!
@IBOutlet weak var toLabel: UILabel!
@IBOutlet weak var createdLabel: UILabel!
var jsonNamesArr: [Any] = []
var jsonAgesArr: [Any] = []
var details = ""
func configureCell(ticket: BookedTickets) {
let fullNames: String = ticket.passangerName!
let dataNameArray = fullNames.data(using: .utf8)
let fullAges: String = ticket.age!
let dataAgeArray = fullAges.data(using: .utf8)
do {
if let jsonNameArray = try JSONSerialization.jsonObject(with: dataNameArray!, options: .allowFragments) as? [Any] {
jsonNamesArr = jsonNameArray
print(jsonNameArray)
}
} catch {
// #error()
print("Error")
}
do {
if let jsonAgeArray = try JSONSerialization.jsonObject(with: dataAgeArray!, options: .allowFragments) as? [Any] {
jsonAgesArr = jsonAgeArray
print(jsonAgeArray)
}
} catch {
print("Error")
}
for (name, age) in zip(jsonNamesArr, jsonAgesArr) {
details = details + ("\(name) of \(age)\n")
print("\(name): \(age)")
}
self.bookerNameLabel.text! = Utilities.getUserName()
//self.ageLabel.text! = "Ages: \(ticket.age!)"
self.passangerNameLabel.text! = "Passangers Details:\n\(details)"
self.fromLabel.text! = "From: \(ticket.fromDestination!)"
self.toLabel.text! = "To: \(ticket.toDestination!)"
self.createdLabel.text! = "Booked Date: \(ticket.created_at!)"
self.ticketNumberLabel.text! = "Ticket Number: \(ticket.uniqueTicketNumber!)"
}
}
My tables images..
Upvotes: 0
Views: 76
Reputation: 70
I am getting customer nil because I am not adding ticket object inside customer object.For that I have created Singleton Class and created Customer property.
import Foundation
class Singleton {
static var user: Customer!
}
and assign customer object to singleton property in login page.
//Singleton
Singleton.user = user
Now singleton object carrying current user object. while saving ticket details add this line Singleton.user.addToTickets(ticket)
You can refer this link
https://github.com/learnasucan/BookTicket.git
Upvotes: 0
Reputation: 285082
You need a predicate for filtering, for example you are looking for all tickets whose name
of the customer
is John Doe
let fetchRequest2 = NSFetchRequest<NSFetchRequestResult>(entityName: "BookedTickets")
let name = "John Doe"
fetchRequest2.predicate = NSPredicate(format: "customer.name = %@", name)
And there is no need to use a completion block in fetch
. The Core Data method fetch(_ request: NSFetchRequest)
works synchronously.
Upvotes: 1