[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[notificationCenter addObserver:self selector:@selector(deviceOrientationDidChange) name:UIDeviceOrientationDidChangeNotification object:nil];
orientation = AVCaptureVideoOrientationPortrait;
I want to know beginGeneratingDeviceOrientationNotifications means what and how to work?
When you write this line:
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
you say to the device:"Please notify the application each time the orientation is changed"
By writing this:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange) name:UIDeviceOrientationDidChangeNotification object:nil];
you say to the application:"Please call deviceOrientationDidChange
method each time you're notified that the orientation is changed".
Now in the deviceOrientationDidChange
you can do the following:
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationPortrait)
[self doSomething];
else
[self doSomethingElse];
Swift 4.2
class ViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: UIDevice.orientationDidChangeNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func deviceOrientationDidChange() {
print(UIDevice.current.orientation.rawValue)
}
}
Swift 3.0
I wish someone had just written this in swift. I know this is an Obj-C post, but I didn't find a swift post like it, so here you go:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func deviceOrientationDidChange() {
print(UIDevice.current.orientation.rawValue)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With