// // ydnabApp.swift // ydnab // // Created by Andrea Franceschini on 20/09/2020. // import UIKit import SwiftUI import os.log class AppDelegate : NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] #if DEBUG print(applicationSupportURL.path) #endif guard !applicationSupportURL.path.isEmpty else { print("Couldn't find Application Support path... something is wrong here.") // TODO: Crash return false } let budgetsListURL = URL(fileURLWithPath: "Budgets.json", relativeTo: applicationSupportURL) if !FileManager.default.fileExists(atPath: budgetsListURL.path) { // TODO: Run onboarding, create first budget let budget: [BudgetSection] = [ BudgetSection(name: "Everyday Expenses", categories: [ BudgetCategory(name: "Groceries"), BudgetCategory(name: "Eating out"), BudgetCategory(name: "Medical"), BudgetCategory(name: "Clothing"), BudgetCategory(name: "Household goods") ]), BudgetSection(name: "Travel", categories: [ BudgetCategory(name: "Transport"), BudgetCategory(name: "Fuel"), BudgetCategory(name: "Accommodation") ]), BudgetSection(name: "Rainy Days", categories: [ BudgetCategory(name: "Emergencies"), BudgetCategory(name: "Car insurance") ]), BudgetSection(name: "Monthly Expenses", categories: [ BudgetCategory(name: "Rent"), BudgetCategory(name: "Mobile") ]), BudgetSection(name: "Savings Goals", categories: [ BudgetCategory(name: "Savings"), BudgetCategory(name: "Holidays") ]) ] let budgetsList: BudgetsList = [ BudgetInfo(name: "Default Budget", localeIdentifier: "en-us", sections: budget) ] let jsonBudget: Data do { let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted jsonBudget = try encoder.encode(budgetsList) try jsonBudget.write(to: budgetsListURL) } catch { print("Couldn't encode budgets list.") print("Error: \(error)") // TODO: Crash? return false } } return true } } @main struct ydnabApp: App { let persistenceController = PersistenceController.shared @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate @Environment(\.scenePhase) private var scenePhase @AppStorage("lastLoadedBudgetId") private var lastLoadedBudgetId = "" var body: some Scene { WindowGroup { NavigationView { BudgetsListView(currentBudgetId: UUID(uuidString: lastLoadedBudgetId)) } .environment(\.managedObjectContext, persistenceController.container.viewContext) } .onChange(of: scenePhase) { phase in print(phase) switch phase { case .background: let context = persistenceController.container.viewContext if context.hasChanges { do { try context.save() } catch { print(error) } } default: print(phase) } } } }