Files
iOS/Sources/Shared/Common/WatchBackgroundRefreshScheduler.swift
mat1th 97834bfd5e Update swift lint and format + appy fixes (#2585)
## Summary
Swift lint and swiftformat are outdated. This PR does update those +
applies the new formatting form swiftformat.
There is 1 swift file with a manual change:
`Sources/Vehicle/Templates/Areas/CarPlayAreasViewModel.swift`. This is
done because `swiftlint` did create the following swiftlint error:
`error: Cyclomatic Complexity Violation: Function should have complexity
10 or less; currently complexity is 11 (cyclomatic_complexity)`.

Because it does change a lot of files the question is if we want to
finetune the `swiftformat` rules.

## Screenshots
No user facing changes.

## Link to pull request in Documentation repository
NA

## Any other notes
NA
2024-02-22 13:06:39 +01:00

47 lines
1.3 KiB
Swift

import Foundation
import PromiseKit
#if os(watchOS)
import WatchKit
#endif
public class WatchBackgroundRefreshScheduler {
public func schedule() -> Guarantee<Void> {
#if os(watchOS)
let (promise, seal) = Guarantee<Void>.pending()
let date = nextFireDate()
WKExtension.shared().scheduleBackgroundRefresh(
withPreferredDate: date,
userInfo: nil,
scheduledCompletion: { error in
Current.Log.info("scheduled for \(date): \(String(describing: error))")
seal(())
}
)
return promise
#else
return .value(())
#endif
}
func nextFireDate() -> Date {
// Apple documents that, if we have an active complication, we can reliably refresh 4 times per hour
// so we divide this into 0 / 15 / 30 / 45
let possibleComponents = stride(from: 0, to: 60, by: 15).map { minute in
with(DateComponents()) {
$0.minute = minute
}
}
let now = Current.date()
let nextPossibilities = possibleComponents.compactMap {
Calendar.current.nextDate(after: now, matching: $0, matchingPolicy: .nextTime)
}.sorted()
return nextPossibilities.first ?? now
}
}