I am pulling data from an API, that data is in the hour/minute interval formatted as a full date, so when I pull the data I am only pulling the last 2 hours of data as to not blow out the memory or cause any issues. Once I get the data I am saving in SwiftData and then showing that info on a chart. The data appears to be showing properly, it's a line chart and the line does have dips and peaks, and I've been dumping out to the console what I'm saving and how many items are being charted and everything looks correct.
My issue is with the annotation, no matter where I click on the chart I am always getting the same date and value from the chart, it never updates to a new value. I can click, release, click somewhere else... same reading. I can click and drag across the chart... same reading. The annotation never updates.
I'm probably just doing something minor that is easily seen, but I just can't see it.
The data I'm pulling from SwiftData is pulled by using a predicate...
let predicate = #Predicate {
$0.timestamp <= start.millisecondsSince1970
}
_entries = Query(filter: predicate, sort: \GlucoseReading.timestamp)
Where start is just...
let start = Calendar.current.date(byAdding: .hour, value: -2, to: Date())
and millisecondsSince1970 is an extension...
extension Date {
var millisecondsSince1970: Int64 {
Int64(self.timeIntervalSince1970 * 1000.0).rounded()
}
}
I then define my chart...
@State var selectedDate: Date? = nil
var body: some View {
Chart(entries) { entry in
LineMark(
x: .value("Date", Date(milliseconds: entry.timestamp)),
y: .value("Glucose", entry.value)
)
RuleMark(y: .value("high", 180))
.foregroundStyle(.red)
RuleMark(y: .value("low", 60))
.foregroundStyle(.red)
if let date = selectedDate {
RuleMark(x: .value("Date", date)
.annotation(
position: .automatic,
overflowResolution: .init(x: .fit(to: .chart), y: .disabled)
) {
//My view code for annotation passing in entry
GlucoseAnnotation(entry: entry)
}
}
}
.chartXSelection(value: $selectedDate)
.padding()
}
The GlucoseAnnotation is really simple, just a VStack with the date and value shown.
In theory that should show me each entry when I click on the chart, however I only get a single entry and date, no matter where I click on the chart. It never updates to a new value, no matter where I click on the chart, I always get the same date and value in the annotation.