Search code examples
swiftswiftuiuiapplication

Swift UIApplication not in scope


I want to change isIdleTimerDisabled when a specific view appears. In SwiftUI I use

.onAppear { 
    UIApplication.shared.isIdleTimerDisabled = true 
}
.onDisappear { 
    UIApplication.shared.isIdleTimerDisabled = false 
}

but even with import UIKit I get the warning

Cannot find 'UIApplication' in scope

How can I fix that? I didn't find a solution after searching for more than an hour.


Solution

  • You should not need to import UIKit, it should work with SwiftUI.

    The problem may be your target. Is the file used only on an iOS or iPadOS application target?

    Or is it also used, for instance, in an extension, like ShareExtension, and so on?

    If it is, you cannot access UIApplication within your code. If this code is shared between extensions and app, you should use conditional compilation to avoid this problem.