I have a view that is set to disappear after 5 seconds and it’s working okay normally aside from this scenario:
- user does the action that makes the view show
- user immediately switch to another app and stays there for a few seconds
user switches back to my app - app is unresponsive
There are no errors in console aside from these
-[RTIInputSystemClient remoteTextInputSessionWithID:performInputOperation:] perform input operation requires a valid sessionID. inputModality = Keyboard, inputOperation = dismissAutoFillPanel, customInfoType = UIUserInteractionRemoteInputOperations
Snapshotting a view (0x109264080, UIKeyboardImpl) that is not in a visible window requires afterScreenUpdates:YES.
Here’s what my code looks like:
class AppState: ObservableObject {
static let shared = AppState()
@Published var notificationArray: [NotificationItem] = []
func addNotification(_ notification: NotificationItem) {
notificationBoxArray.append(notification)
}
func removeNotification(_ notification: NotificationItem) {
self.notificationBoxArray.removeAll { $0.id == notification.id }
}
}
struct NotificationBoxModifier: ViewModifier {
func body(content: Content) -> some View {
content
.frame(maxWidth: .infinity, maxHeight: .infinity)
.overlay(
ZStack {
mainNotificationBoxView()
}.animation(.spring(), value: AppState.shared.notificationBoxArray)
)
.enableInjection()
}
#if DEBUG
@ObserveInjection var forceRedraw
#endif
@ViewBuilder func mainNotificationBoxView() -> some View {
if AppState.shared.notificationArray.count > 0 {
VStack {
ForEach(AppState.shared.notificationArray){ notification in
NotificationBoxView(notificationText: notification.message, notificationType: notification.type) {}
.padding(.bottom,16)
.task {
do {
try await Task.sleep(seconds: 5)
await MainActor.run {
AppState.shared.removeNotification(notification)
}
} catch {
logger.error("Task.sleep error (error.localizedDescription)")
}
}
}
Spacer()
}
.transition(.move(edge: .top))
}
}
}
Previously the task happens in the addNotification
box and the issue is still present
func addNotification(_ notification: NotificationItem) {
notificationBoxArray.append(notification)
Task {
do {
try await Task.sleep(seconds: 5)
await MainActor.run {
AppState.shared.removeNotification(notification)
}
} catch {
logger.error("Task.sleep error (error.localizedDescription)")
}
}
}
I also tried commenting out the task and the deletion of the notification and the freeze is gone so the problem is really in the .task
New contributor
smekers is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.