comparison Simoleon/FavoritesView.swift @ 171:70f0625bfcf1

Merge pull request #17 from denniscm190/development open source project committer: GitHub <noreply@github.com>
author Dennis C. M. <dennis@denniscm.com>
date Tue, 12 Oct 2021 16:17:35 +0200
parents e4cbb1eea394
children
comparison
equal deleted inserted replaced
146:f10b0e188905 171:70f0625bfcf1
1 //
2 // FavoritesView.swift
3 // Simoleon
4 //
5 // Created by Dennis Concepción Martín on 19/07/2021.
6 //
7
8 import SwiftUI
9
10 struct FavoritesView: View {
11 @Environment(\.managedObjectContext) private var viewContext
12 @FetchRequest(
13 sortDescriptors: [NSSortDescriptor(keyPath: \FavoritePair.baseSymbol, ascending: true)],
14 animation: .default)
15 private var favoritePairs: FetchedResults<FavoritePair>
16
17 var body: some View {
18 VStack {
19 if favoritePairs.isEmpty {
20 FavoritesPlaceholder()
21 } else {
22 List {
23 ForEach(favoritePairs, id:\.self) { favoritePair in
24 FavoritePairRow(favoritePair: favoritePair)
25 .padding(.vertical, 4)
26 }
27 .onDelete(perform: removeFromFavorites)
28 }
29 .listStyle(InsetGroupedListStyle())
30 }
31 }
32 .navigationTitle("Favorites")
33 .toolbar {
34 #if os(iOS)
35 EditButton()
36 #endif
37 }
38 .if(UIDevice.current.userInterfaceIdiom == .phone) { content in
39 NavigationView { content }
40 }
41 .onAppear {
42 #if SCREENSHOTS
43 generateFavoritesForScreenshots()
44 #endif
45 }
46 }
47
48 private func removeFromFavorites(offsets: IndexSet) {
49 withAnimation {
50 offsets.map { favoritePairs[$0] }.forEach(viewContext.delete)
51
52 do {
53 try viewContext.save()
54 } catch {
55 let nsError = error as NSError
56 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
57 }
58 }
59 }
60
61 #if SCREENSHOTS
62 /*
63 Save currencies to favourites to take screenshots for the App Store
64 */
65 private func generateFavoritesForScreenshots() {
66 let pairs = ["EUR/USD", "BTC/USD", "USD/HKD", "USD/JPY", "AUD/USD",
67 "XAU/GBP", "DASH/ETH", "EUR/USD", "XAG/CAD"]
68
69 for pair in pairs {
70 let symbols = pair.components(separatedBy: "/")
71 let favoritePair = favoritePairs.first(
72 where: {
73 $0.baseSymbol == symbols[0] && $0.quoteSymbol == symbols[1]
74 })
75
76 if let _ = favoritePair {
77 // Do not save to core data again
78 } else {
79 let favoritePair = FavoritePair(context: viewContext)
80 favoritePair.baseSymbol = symbols[0]
81 favoritePair.quoteSymbol = symbols[1]
82 }
83
84 do {
85 try viewContext.save()
86 } catch {
87 let nsError = error as NSError
88 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
89 }
90 }
91 }
92 #endif
93 }
94
95 struct FavoritesView_Previews: PreviewProvider {
96 static var previews: some View {
97 FavoritesView()
98 .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
99 }
100 }