Reputation: 83
[[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?
Upvotes: 7
Views: 10236
Reputation: 6599
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)
}
}
Upvotes: 7
Reputation: 123
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
This is optional to get notifications. Please, share if anybody knows how it works.
Upvotes: 2
Reputation: 21808
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];
Upvotes: 26