I am building a Quiz app in swift (my first app) to practice a few skills (using CoreData, working with plists, UIKit etc.) and later to work with a server which stores the Exercises.
Here's my current point in development: https://bitbucket.org/paescebu/staplerch/src/master/
My question is not precise, more general, I hope this is accepted here. I wanted to know if what I am practicing in my Code is good or bad practice so far. Any specifics like: - Design pattern - Conventions - bad practices are welcome
example of my uncertainties (my AppDelegate):
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
preloadData()
return true
}
private func preloadData() {
let preloadedDataKey = "didPreloadData"
let userDefaults = UserDefaults.standard
if userDefaults.bool(forKey: preloadedDataKey) == false
{
var categories: [Category] = []
if let path = Bundle.main.path(forResource: "demoExercises", ofType: "plist") {
categories = readDemoDataPlist(withPath: path)
}
//preload into Core Data
let backgroundContext = persistentContainer.newBackgroundContext()
persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
backgroundContext.perform
{
do {
for item in categories {
let category = CDCategory(context: backgroundContext)
category.title = item.title
category.imageName = item.imageName
if let exerciseArray = item.exercises {
for eachExercise in exerciseArray {
let exercise = CDExercise(context: backgroundContext)
exercise.question = eachExercise.question
exercise.explanation = eachExercise.explanation
exercise.imageName = eachExercise.imageName
exercise.correctAnswer = eachExercise.correctAnswer
if let answersArray = eachExercise.answers
{
for eachAnswer in answersArray {
let answer = CDAnswers(context: backgroundContext)
answer.answer = eachAnswer
exercise.addToAnswers(answer)
}
}
category.addToExercises(exercise)
}
}
}
try backgroundContext.save()
userDefaults.set(true, forKey: preloadedDataKey)
print("Sucess!")
}
catch {
print("failed saving Context:\(error.localizedDescription)")
}
}
}
}
func readDemoDataPlist(withPath: String) -> [Category] {
var categoriesArray : [Category] = []
if let arrayWithCategories = NSArray(contentsOfFile: withPath) as? [[String : Any]] {
for eachCategory in arrayWithCategories {
let category = Category()
if let categoryTitle = eachCategory["title"] as? String {
category.title = categoryTitle
}
if let categoryImage = eachCategory["imageName"] as? String {
category.imageName = categoryImage
}
if let arrayWithExercises = eachCategory["exercises"] as? [[String : Any]] {
var exerciseArray: [Exercise] = []
for eachExercise in arrayWithExercises {
let exercise = Exercise()
if let question = eachExercise["question"] as? String {
exercise.question = question
}
if let correctAnswerIndex = eachExercise["correctAnswer"] as? String {
exercise.correctAnswer = correctAnswerIndex
}
if let answers = eachExercise["answers"] as? [String] {
exercise.answers = answers
}
if let image = eachExercise["image"] as? String {
exercise.imageName = image
}
if let explanation = eachExercise["explanation"] as? String {
exercise.explanation = explanation
}
exerciseArray.append(exercise)
category.exercises = exerciseArray
}
}
categoriesArray.append(category)
}
}
return categoriesArray
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// 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: "StaplerCH")
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)")
}
}
}
}
UPDATE
I changed it quite a bit now, directly using the NSManagedObject model created from CoreData, instead of this step in between storing from plist, and the reading into persistent store.
Looks now like this:
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
preloadData()
return true
}
private func preloadData() {
let preloadedDataKey = "didPreloadData"
let userDefaults = UserDefaults.standard
if userDefaults.bool(forKey: preloadedDataKey) == false
{
if let path = Bundle.main.path(forResource: "demoExercises", ofType: "plist")
{
if let arrayWithCategories = NSArray(contentsOfFile: path) as? [[String : Any]]
{
//preload into Core Data
let backgroundContext = persistentContainer.newBackgroundContext()
persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
backgroundContext.perform {
do {
for eachCategory in arrayWithCategories {
let category = Category(context: backgroundContext)
if let categoryTitle = eachCategory["title"] as? String {
category.title = categoryTitle
}
if let categoryImage = eachCategory["imageName"] as? String {
category.imageName = categoryImage
}
if let exerciseArray = eachCategory["exercises"] as? [[String: Any]] {
for eachExercise in exerciseArray {
let exercise = Exercise(context: backgroundContext)
if let question = eachExercise["question"] as? String {
exercise.question = question
}
if let image = eachExercise["image"] as? String {
exercise.imageName = image
}
if let explanation = eachExercise["explanation"] as? String {
exercise.explanation = explanation
}
if let arrayWithAnswers = eachExercise["answers"] as? [[String : Any]] {
for eachAnswer in arrayWithAnswers {
if let answerText = eachAnswer["text"] as? String, let answerIsCorrect = eachAnswer["isCorrect"] as? Bool {
let answer = Answer(context: backgroundContext)
answer.text = answerText
answer.isCorrect = answerIsCorrect
exercise.addToAnswers(answer)
}
}
}
category.addToExercises(exercise)
}
}
}
try backgroundContext.save()
userDefaults.set(true, forKey: preloadedDataKey)
print("Sucess!")
}
catch {
print("failed saving Context:\(error.localizedDescription)")
}
}
}
}
}
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// 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: "StaplerCH")
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)")
}
}
}
}
Short workflow: After first installation, the app will load some demoQuestions from a plist into the persistent Store using the CoreData stack, so that the app is already preloaded with some Exercises, as said, in a later stage I'd like to be able to keep Exercises on a server from which the user can keep the Exercises updated.
The App has 2 Modes, a Practice and an Exam Mode (depending of the mode the ExerciseVC behaves differently), I really tried hard to have one VC only for that.
The other two Pages of the Start Page are quite irrelevant so far.
I am very thankful for any input.