Mercurial > public > simoleon
diff Simoleon/Settings.swift @ 23:699b5bb619db
UserSettings CoreData implemented
author | Dennis Concepción Martín <dennisconcepcionmartin@gmail.com> |
---|---|
date | Tue, 20 Jul 2021 09:54:41 +0100 |
parents | 3596690dda73 |
children | bda6a55d027a |
line wrap: on
line diff
--- a/Simoleon/Settings.swift Tue Jul 20 09:02:51 2021 +0100 +++ b/Simoleon/Settings.swift Tue Jul 20 09:54:41 2021 +0100 @@ -8,8 +8,10 @@ import SwiftUI struct Settings: View { + @Environment(\.managedObjectContext) private var viewContext + @FetchRequest(sortDescriptors: []) private var userSettings: FetchedResults<UserSettings> + @State private var selectedCurrencyPair = "USD/GBP" let currencyPairs: [String] = parseJson("CurrencyPairs.json") - @State private var selectedCurrencyPair = "USD/GBP" var body: some View { List { @@ -19,15 +21,20 @@ Text(currencyPair) } } + .onChange(of: selectedCurrencyPair, perform: { selectedCurrencyPair in + setDefaultCurrency() + }) } Section(header: Text("Stay in touch")) { - HStack { - Image(systemName: "heart.fill") - .foregroundColor(Color(.systemRed)) - .imageScale(.large) - - Text("Rate Simoleon") + Link(destination: URL(string: "https://itunes.apple.com/app/id1576390953?action=write-review")!) { + HStack { + Image(systemName: "heart.fill") + .foregroundColor(Color(.systemRed)) + .imageScale(.large) + + Text("Rate Simoleon") + } } Link(destination: URL(string: "https://dennistech.io")!) { @@ -54,14 +61,42 @@ Section(header: Text("About")) { Link("Website", destination: URL(string: "https://dennistech.io")!) Link("Privacy Policy", destination: URL(string: "https://dennistech.io")!) + Link("Developer's Twitter", destination: URL(string: "https://twitter.com/dennisconcep")!) } } + .onAppear(perform: fetchUserSettings) .listStyle(InsetGroupedListStyle()) .navigationTitle("Settings") .if(UIDevice.current.userInterfaceIdiom == .phone) { content in NavigationView { content } } } + + /* + 1) Fetch default currency from User Settings + 2) Change State var currencyPair + */ + private func fetchUserSettings() { + if let userSettings = userSettings.first { + self.selectedCurrencyPair = userSettings.defaultCurrency ?? "USD/GBP" + } + } + + private func setDefaultCurrency() { + if self.userSettings.isEmpty { /// If it's empty -> add record + let userSettings = UserSettings(context: viewContext) + userSettings.defaultCurrency = selectedCurrencyPair + + do { + try viewContext.save() + } catch { + print(error.localizedDescription) + } + } else { /// If not, update record + self.userSettings.first?.defaultCurrency = selectedCurrencyPair + try? viewContext.save() + } + } } struct Settings_Previews: PreviewProvider {