4

I am looking for a way to get safe area inset values for the top and bottom of the screen (to position content correctly in order to make it not covered by a notch or software home button).

I looked around stackoverflow and was able to find this approach, however I am getting deprecation warning in XCode saying that keyWindow should not be used.

let window = UIApplication.shared.keyWindow
let topPadding = window?.safeAreaInsets.top
let bottomPadding = window?.safeAreaInsets.bottom
Ilja
  • 44,142
  • 92
  • 275
  • 498

3 Answers3

7

After iOS13 keyWindow concept in iOS anymore as a single app can have multiple windows. So just take the first one :

    let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
    let topPadding = window?.safeAreaInsets.top
    let bottomPadding = window?.safeAreaInsets.bottom
    
zeytin
  • 5,545
  • 4
  • 14
  • 38
1

You could try using the view controller view to get the safe area, or you can solve the deprecation as below:

let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
let topPadding = window?.safeAreaInsets.top
let bottomPadding = window?.safeAreaInsets.bottom

See also : https://stackoverflow.com/a/57899013/3172445

Luca Iaco
  • 3,387
  • 1
  • 19
  • 20
0

Try this solution:

let topPadding: CGFloat
let bottomPadding: CGFloat
        if #unavailable(iOS 15) {
            topPadding = UIApplication.shared.windows.first?.safeAreaInsets.top ?? 0
            bottomPadding = UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0
        } else {
            topPadding = UIApplication
                .shared
                .connectedScenes
                .flatMap { ($0 as? UIWindowScene)?.windows ?? [] }
                .first { $0.isKeyWindow }?.safeAreaInsets.top ?? 0
            
            bottomPadding = UIApplication
                .shared
                .connectedScenes
                .flatMap { ($0 as? UIWindowScene)?.windows ?? [] }
                .first { $0.isKeyWindow }?.safeAreaInsets.bottom ?? 0
        }