Я сохраняю информацию из двух таблиц, используя основные данные: один - Клиент, а другой - Забронированные билеты.один клиент может забронировать много билетов.Я хочу получить эти связанные данные и заполнить их в виде таблицы. Я получаю все данные о билетах, но мне нужна информация о билетах конкретного пользователя.например users.ticket.passangerName.Но я получаю ноль здесь.
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
}
}
В клетке ...
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!)"
}
}
Мои изображения таблиц ..