Mercurial > public > lazybear
diff LazyBear/Views/Search/Helpers/SearchedCompanyItem.swift @ 389:db8bc3ed526a
Implementing add to watchlist feature from SearchView
author | Dennis Concepción Martín <66180929+denniscm190@users.noreply.github.com> |
---|---|
date | Sun, 25 Apr 2021 16:42:26 +0200 |
parents | 280cbc5653b5 |
children | 8ec37b2baafd |
line wrap: on
line diff
--- a/LazyBear/Views/Search/Helpers/SearchedCompanyItem.swift Sat Apr 24 17:44:02 2021 +0200 +++ b/LazyBear/Views/Search/Helpers/SearchedCompanyItem.swift Sun Apr 25 16:42:26 2021 +0200 @@ -10,8 +10,28 @@ struct SearchedCompanyItem: View { var company: SearchResponse + @Environment(\.managedObjectContext) private var moc + @FetchRequest(entity: WatchlistCompany.entity(), sortDescriptors: []) + var watchlistCompany: FetchedResults<WatchlistCompany> + + @State private var showingActionSheet = false + var body: some View { + let watchlistSymbols = watchlistCompany.map { $0.symbol } HStack { + Button(action: { self.showingActionSheet = true }) { + if watchlistSymbols.contains(company.symbol!) { + Image(systemName: "star.fill") + .foregroundColor(.yellow) + .imageScale(.large) + } else { + Image(systemName: "star") + .foregroundColor(.yellow) + .imageScale(.large) + } + } + .buttonStyle(PlainButtonStyle()) + VStack(alignment: .leading) { Text(company.symbol!.uppercased()) .fontWeight(.semibold) @@ -29,6 +49,41 @@ Text(company.region!) } } + .actionSheet(isPresented: $showingActionSheet) { + ActionSheet(title: Text("Your watchlists"), message: Text("Select"), buttons: generateButtons()) + } + } + + // Get watchlist names -> generate buttons + private func generateButtons() -> [ActionSheet.Button] { + var actionButtons = [ActionSheet.Button]() + let watchlists = Set(watchlistCompany.map { $0.watchlist }) + + for watchlistName in watchlists { + actionButtons.append( + .default(Text(watchlistName)) { + addCompany(company.symbol!, company.securityName!, watchlistName) + } + ) + } + + actionButtons.append(.cancel()) + + return actionButtons + } + + // Add to watchlist + private func addCompany(_ symbol: String, _ name: String, _ watchlist: String) { + let watchlistCompany = WatchlistCompany(context: moc) + watchlistCompany.symbol = symbol + watchlistCompany.name = name + watchlistCompany.watchlist = watchlist + do { + try moc.save() + print("Company saved") + } catch { + print(error.localizedDescription) + } } }