EN_Tech
EN_Tech

Reputation: 107

SwiftUI view with warning for 'keyWindow' was deprecated in iOS 13.0 in safeAreaInsets

It creates crash and also generate warning in my code

My use of code :- .offset(y: self.originTextField.y + UIApplication.shared.keyWindow!.safeAreaInsets.top + 52)

Warning

'keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes

Log

Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x28396b700 'BIB_Leading_Leading' H:|-(0)-[_UIModernBarButton:0x103fad930]   (active, names: '|':_UIButtonBarButton:0x103facda0 )>",
    "<NSLayoutConstraint:0x28397c460 'UINav_static_button_horiz_position' _UIModernBarButton:0x103fad930.leading == UILayoutGuide:0x28232e680'UIViewLayoutMarginsGuide'.leading   (active)>",
    "<NSLayoutConstraint:0x28397c4b0 'UINavItemContentGuide-leading' H:[_UIButtonBarButton:0x103facda0]-(6)-[UILayoutGuide:0x28232e4c0'UINavigationBarItemContentLayoutGuide']   (active)>",
    "<NSLayoutConstraint:0x283969f40 'UINavItemContentGuide-trailing' UILayoutGuide:0x28232e4c0'UINavigationBarItemContentLayoutGuide'.trailing == _UINavigationBarContentView:0x103fabfd0.trailing   (active)>",
    "<NSLayoutConstraint:0x2839799a0 'UIView-Encapsulated-Layout-Width' _UINavigationBarContentView:0x103fabfd0.width == 0   (active)>",
    "<NSLayoutConstraint:0x28396a300 'UIView-leftMargin-guide-constraint' H:|-(8)-[UILayoutGuide:0x28232e680'UIViewLayoutMarginsGuide'](LTR)   (active, names: '|':_UINavigationBarContentView:0x103fabfd0 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x28396b700 'BIB_Leading_Leading' H:|-(0)-[_UIModernBarButton:0x103fad930]   (active, names: '|':_UIButtonBarButton:0x103facda0 )>

Upvotes: 0

Views: 555

Answers (1)

Aye Chan
Aye Chan

Reputation: 1427

As iOS 13 comes with multi-scene support, you need to rely on connectedScenes to retrieve the active window. You can use the following extension to get the active window and then can access safeAreaInsets from that window.

// MARK: - UIApplication+Extension
extension UIApplication {
    var keyWindow: UIWindow? {
        return UIApplication.shared
            .connectedScenes
            .first(where: { $0 is UIWindowScene })
            .flatMap { $0 as? UIWindowScene }?.windows
            .first(where: \.isKeyWindow)
    }
}

// MARK: - Usage
.offset(y: UIApplication.shared.keyWindow?.safeAreaInsets.top ?? 0)

Upvotes: 1

Related Questions