Skip to content

Commit

Permalink
Fix steps query end date off by 1 (#218)
Browse files Browse the repository at this point in the history
  • Loading branch information
EvanCooper9 authored Mar 19, 2024
1 parent cffaf91 commit 98801fa
Showing 1 changed file with 28 additions and 29 deletions.
57 changes: 28 additions & 29 deletions FriendlyCompetitions/Managers/StepCount/StepCountManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,40 +40,39 @@ final class StepCountManager: StepCountManaging {

func stepCounts(in dateInterval: DateInterval) -> AnyPublisher<[StepCount], Error> {
guard let days = Calendar.current.dateComponents([.day], from: dateInterval.start, to: dateInterval.end).day else { return .just([]) }
return (0 ..< days)
.compactMap { offset -> AnyPublisher<StepCount?, Never>? in
let start = Calendar.current
.startOfDay(for: dateInterval.start)
.addingTimeInterval(TimeInterval(offset).days)

guard start <= .now else {
return nil
}
return (0 ... days).compactMap { offset -> AnyPublisher<StepCount?, Never>? in
let start = Calendar.current
.startOfDay(for: dateInterval.start)
.addingTimeInterval(TimeInterval(offset).days)

guard start <= .now else {
return nil
}

let end = Calendar.current
.startOfDay(for: start)
.addingTimeInterval(24.hours - 1.seconds)

let predicate = HKQuery.predicateForSamples(withStart: start, end: end)
return Future<StepCount?, Error> { [weak self] promise in
let query = StepsQuery(predicate: predicate) { result in
switch result {
case .failure(let error):
promise(Result<StepCount?, Error>.failure(error))
case .success(let steps):
let count = StepCount(count: Int(steps), date: start)
promise(.success(count))
}
let end = Calendar.current
.startOfDay(for: start)
.addingTimeInterval(24.hours - 1.seconds)

let predicate = HKQuery.predicateForSamples(withStart: start, end: end)
return Future<StepCount?, Error> { [weak self] promise in
let query = StepsQuery(predicate: predicate) { result in
switch result {
case .failure(let error):
promise(Result<StepCount?, Error>.failure(error))
case .success(let steps):
let count = StepCount(count: Int(steps), date: start)
promise(.success(count))
}
self?.healthKitManager.execute(query)
}
.catchErrorJustReturn(nil)
.eraseToAnyPublisher()
self?.healthKitManager.execute(query)
}
.combineLatest()
.compactMapMany { $0 }
.setFailureType(to: Error.self)
.catchErrorJustReturn(nil)
.eraseToAnyPublisher()
}
.combineLatest()
.compactMapMany { $0 }
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}

// MARK: - Private Methods
Expand Down

0 comments on commit 98801fa

Please sign in to comment.