I have set up the app delegate, constants and view controller to display the JSON file data in a tableView. Similar to the GuideBook CoreData course. A few months ago the application worked as intended with the JSON file data loading into the tableView however ever since updating to the latest version of Xcode, the JSON file data does not appear in the tableView. I can still create, update, delete, if I manually put in an entry by clicking the “add” button within the app but I need to have the JSON file data preloaded.
App Delegate:
import UIKit
import CoreData
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
preloadData()
return true
}
private func preloadData() {
let defaults = UserDefaults.standard
let context = persistentContainer.viewContext
if !defaults.bool(forKey: Constants.PRELOAD_DATA) {
guard let path = Bundle.main.path(forResource: "Person", ofType: "json") else {
print("Failed to get path to JSON file")
return
}
do {
let url = URL(fileURLWithPath: path)
let data = try Data(contentsOf: url)
let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [[String: Any]]
for json in jsonArray {
let person = Person(context: context)
person.servicenumber = json["servicenumber"] as? String
person.rank = json["rank"] as? String
person.initials = json["initials"] as? String
person.firstname = json["firstname"] as? String
person.middlename = json["middlename"] as? String
person.lastname = json["lastname"] as? String
person.service = json["service"] as? String
person.corps = json["corps"] as? String
person.unit = json["unit"] as? String
person.gender = json["gender"] as? String
person.dateOfbirth = json["dateOfbirth"] as? String
person.address = json["address"] as? String
person.location = json["location"] as? String
person.phone = json["phone"] as? String
}
saveContext()
defaults.set(true, forKey: Constants.PRELOAD_DATA)
} catch {
print("Error loading data: \(error)")
}
}
}
// ... the rest of the class implementation
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "ContactFront")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
PersonViewController:
import UIKit
import CoreData
class PersonViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchControllerDelegate, UISearchBarDelegate {
private let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
var person = [Person]()
let searchController = UISearchController()
override func viewDidLoad() {
super.viewDidLoad()
title = "Query Person"
tableView.dataSource = self
tableView.delegate = self
searchController.delegate = self
searchBar.delegate = self
fetchPeople()
}
func fetchPeople() {
do {
self.person = try context.fetch(Person.fetchRequest())
tableView.reloadData()
}
catch {
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
@IBAction func addButtonPressed(_ sender: Any) {
let alert = UIAlertController(title: "Add New Person", message: "", preferredStyle: .alert)
//Add name
alert.addTextField { servicenumber in
servicenumber.placeholder = "Service Number"
}
//Add phone number
alert.addTextField { rank in
rank.placeholder = "Rank"
}
alert.addTextField { initials in
initials.placeholder = "Initials"
}
alert.addTextField { firstname in
firstname.placeholder = "First Name"
}
alert.addTextField { middlename in
middlename.placeholder = "Middle Name"
}
alert.addTextField { lastname in
lastname.placeholder = "Last Name"
}
alert.addTextField { service in
service.placeholder = "Service"
}
alert.addTextField { corps in
corps.placeholder = "Corps"
}
alert.addTextField { unit in
unit.placeholder = "Unit"
}
alert.addTextField { gender in
gender.placeholder = "Gender"
}
alert.addTextField { dateOfbirth in
dateOfbirth.placeholder = "DOB"
}
alert.addTextField { address in
address.placeholder = "Address"
}
alert.addTextField { location in
location.placeholder = "Location"
}
alert.addTextField { phone in
phone.placeholder = "Phone"
}
let action = UIAlertAction(title: "Add", style: .default) { action in
let newContact = Person(context: self.context)
newContact.servicenumber = alert.textFields![0].text
newContact.rank = alert.textFields![1].text
newContact.initials = alert.textFields![2].text
newContact.firstname = alert.textFields![3].text
newContact.middlename = alert.textFields![4].text
newContact.lastname = alert.textFields![5].text
newContact.service = alert.textFields![6].text
newContact.corps = alert.textFields![7].text
newContact.unit = alert.textFields![8].text
newContact.gender = alert.textFields![9].text
newContact.dateOfbirth = alert.textFields![10].text
newContact.address = alert.textFields![11].text
newContact.location = alert.textFields![12].text
newContact.phone = alert.textFields![13].text
if let phoneText = alert.textFields?[13] {
newContact.phone = phoneText.text
}
self.person.append(newContact)
self.saveContacts()
}
let cancel = UIAlertAction(title: "Cancel", style: .default) { cancel in
print("Cancel")
}
alert.addAction(action)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if tableView.indexPathForSelectedRow == nil{
return
}
let selectedContact = self.person[tableView.indexPathForSelectedRow!.row]
let personVC = segue.destination as! PersonContainerViewController
personVC.person = selectedContact
}
func saveContacts(){
do{
try context.save()
}
catch {
print("Error saving data: \(error)")
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return person.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//Cell reference
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.PERSON_CELL) as! PersonTableViewCell
//Get the person
let p = self.person[indexPath.row]
cell.setCell(p: p)
return cell
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
let appDe = (UIApplication.shared.delegate) as! AppDelegate
let context=appDe.persistentContainer.viewContext
let request : NSFetchRequest<Person> = Person.fetchRequest()
let predicate = NSPredicate(format: "(servicenumber CONTAINS[cd] %@) OR (lastname CONTAINs[cd] %@) OR (firstname CONTAINS[cd] %@)", searchBar.text!, searchBar.text!, searchBar.text!)
request.predicate = predicate
request.sortDescriptors = [NSSortDescriptor(key: "servicenumber", ascending: true)]
do {
person = try context.fetch(request)
} catch {
print("Error fetching data: \(error)")
}
self.tableView.reloadData()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.count == 0 { // Use the passed in searchText parameter instead of searchBar.text?.count
fetchPeople()
self.tableView.reloadData()
DispatchQueue.main.async {
searchBar.resignFirstResponder()
}
} else {
}
}
}