Hi Basel,
I had this issue with WatchOS whose apps are going to the background whenever you do a wrist down (which is kind of annoying)
I solved this problem like this:
I created a new Timer class. The SwiftUI Timer freezes and slows down on WatchOS, therefore I used a custom one. You can use the SwiftUI one if you want as you are using iOS
File StopWatchManager.swift
import SwiftUI
class StopWatchManager: ObservableObject {
@Published var secondsElapsed: Int = 0
var timer: Timer = Timer()
func start() {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
self.secondsElapsed += 1
}
}
func stop() {
timer.invalidate()
secondsElapsed = 0
}
func pause() {
timer.invalidate()
}
}
Then you have to pause the timer whenever your app goes to the background and restart it whenever your app is going to the foreground. You can do it like this:
import UserNotifications
Add a notificationDate state:
@State private var notificationDate: Date = Date()
Create 1 function to request persmission for UserNotifications
func requestPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
print("All set!")
} else if let error = error {
print(error.localizedDescription)
}
}
}
Add 2 custom functions for dealing with moving between background and foreground:
// MARK: - Custom User Notifications
func movingToBackground() {
print("Moving to the background")
notificationDate = Date()
stopWatchManager.pause()
}
func movingToForeground() {
print("Moving to the foreground")
let deltaTime: Int = Int(Date().timeIntervalSince(notificationDate))
stopWatchManager.secondsElapsed += deltaTime
stopWatchManager.start()
}
Add this modifier to the view for requesting permission:
.onAppear(perform: requestPermission)
Finally, add those 2 modifiers for calling the right function at the right time. I used WKExtension notifications for watchOS but you can use the iOS ones:
.onReceive(NotificationCenter.default.publisher(
for: WKExtension.applicationWillResignActiveNotification
)) { _ in
movingToBackground()
}
.onReceive(NotificationCenter.default.publisher(
for: WKExtension.applicationDidBecomeActiveNotification
)) { _ in
movingToForeground()
}
This setup works perfectly fine on WatchOS, therefore it should work even better on iOS
Let me know if it solves your problem