1

I want to get notified when user changes iPad orientation. In UIKit that was easy but I do not know how we can get that information with SwiftUI?

pawello2222
  • 46,897
  • 22
  • 145
  • 209
ios coder
  • 1
  • 4
  • 31
  • 91

1 Answers1

1

You can try:

UIApplication.shared.windows.first?.windowScene?.interfaceOrientation.isLandscape ?? false

or:

UIDevice.current.orientation.isLandscape

If you want to detect notifications you can listen to UIDevice.orientationDidChangeNotification:

UIDevice.current.beginGeneratingDeviceOrientationNotifications()
...
.onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { ... }

Here is a demo:

@main
struct TestApp: App {
    init() {
        UIDevice.current.beginGeneratingDeviceOrientationNotifications()
    }

    var body: some Scene {
        WindowGroup {
            Text("Test")
                .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
                    print(UIApplication.shared.windows.first?.windowScene?.interfaceOrientation.isLandscape ?? false)
                }
        }
    }
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • @Omid It works for me without changing the orientation (Xcode 12.0.1). – pawello2222 Oct 18 '20 at 19:05
  • @Omid Added a demo to my answer. – pawello2222 Oct 18 '20 at 19:10
  • @Omid Works for me with `UIDevice.current.orientation.isLandscape` as well. You may try to add `UIDevice.current.beginGeneratingDeviceOrientationNotifications()` – pawello2222 Oct 18 '20 at 19:19
  • @Omid This is not a notification - please see my updated demo. – pawello2222 Oct 18 '20 at 19:25
  • @Omid Worst case your app will crash. But there is no need to unwrap it. If it's nil then you won't be detecting the orientation change. – pawello2222 Oct 18 '20 at 20:27
  • @Omid `??` is not force unwrapping, it will not crash the application if used on `nil` (unlike `!`). My recommendation: never force unwrap. Use `if`, `guard let`, `if let` etc. See [What is the nil coalescing operator?](https://www.hackingwithswift.com/example-code/language/what-is-the-nil-coalescing-operator) – pawello2222 Oct 18 '20 at 21:48