krz/domain-dig
an ios app for DNS & SSL analysis
clone: git clone https://gitbay.org/krz/domain-dig.git
v4.8.2: DomainDig/SweepActivityController.swift · raw
1import ActivityKit
2import Foundation
3
4/// Starts, updates, and ends the sweep Live Activity around a batch run.
5@MainActor
6final class SweepActivityController {
7 static let shared = SweepActivityController()
8
9 private var activity: Activity<SweepActivityAttributes>?
10
11 private init() {}
12
13 func begin(title: String, total: Int) {
14 guard ActivityAuthorizationInfo().areActivitiesEnabled else { return }
15 // A previous activity that never ended (e.g. app killed mid-sweep)
16 // would otherwise linger; replace it.
17 end(changed: 0, warnings: 0, immediately: true)
18
19 let state = SweepActivityAttributes.ContentState(
20 completed: 0,
21 total: total,
22 currentDomain: nil,
23 changed: 0,
24 warnings: 0
25 )
26 activity = try? Activity.request(
27 attributes: SweepActivityAttributes(title: title, startedAt: Date()),
28 content: ActivityContent(state: state, staleDate: nil)
29 )
30 }
31
32 func update(completed: Int, total: Int, currentDomain: String?) {
33 guard let activity else { return }
34 let state = SweepActivityAttributes.ContentState(
35 completed: completed,
36 total: total,
37 currentDomain: currentDomain,
38 changed: 0,
39 warnings: 0
40 )
41 Task {
42 await activity.update(ActivityContent(state: state, staleDate: nil))
43 }
44 }
45
46 func end(changed: Int, warnings: Int, immediately: Bool = false) {
47 guard let activity else { return }
48 self.activity = nil
49 let state = SweepActivityAttributes.ContentState(
50 completed: activity.content.state.total,
51 total: activity.content.state.total,
52 currentDomain: nil,
53 changed: changed,
54 warnings: warnings
55 )
56 Task {
57 await activity.end(
58 ActivityContent(state: state, staleDate: nil),
59 dismissalPolicy: immediately ? .immediate : .after(Date().addingTimeInterval(60))
60 )
61 }
62 }
63}