0

I'm trying to implement a chart in Swift UI based on specific dates for an expenses app. I can get the total amount per month & display each, but I'm stuck on showing payments for a specific month (.i.e last month, current month) split by weeks.

I'm fetching payment data from Firestore, but can only fetch all data rather than just for dates as far as I know?

                Chart {
                    ForEach(paymentModel.payments) { payment in
                        BarMark(
                            x: .value("month", payment.paymentDate, unit: .weekOfMonth),
                            y: .value("Amount", payment.paymentAmount)
                        )
                        
                    }
                }
                .frame(height: 180)
                .padding()
                .chartXAxis {
                    AxisMarks() { date in
                        AxisValueLabel(format: .dateTime.week(), centered: true)
                        
                        
                    }
                }
                .onAppear() {
                    self.paymentModel.getAllPayments()
                }
                
        }
    }
    

            
        }

Thanks!

I've used the total amount but not sure how to get show payments based only on a certain month or other criteria (like a category)

H121
  • 1
  • 1

1 Answers1

1

you need to filter it first. now as for charts its a little tricky I am still trying to find out how to do that. but say you want to see a list of the transactions that are done this week or only today you can use a filter like this:

func filteredTransactions(for category: Category, in timeFrame: TimeFrame) -> [FinancialTransaction] {
    let now = Date()
    let calendar = Calendar.current

    let filteredTransactions = category.transactions.filter { transaction in
        let components: DateComponents
        switch timeFrame {
        case .day:
            components = calendar.dateComponents([.day], from: transaction.date, to: now)
            return components.day! < 1
        case .week:
            components = calendar.dateComponents([.weekOfYear], from: transaction.date, to: now)
            return components.weekOfYear! < 1
        case .month:
            components = calendar.dateComponents([.month], from: transaction.date, to: now)
            return components.month! < 1
        case .year:
            components = calendar.dateComponents([.year], from: transaction.date, to: now)
            return components.year! < 1
        }
    }

    return filteredTransactions
}

I am Trying to implement this filter with charts ones I succeed I'll let you know so you can use it too. you can also change the filter by showing you a custom date also.