Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

beginGeneratingDeviceOrientationNotifications How to work

    [[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?

like image 216
chenhongbin Avatar asked Apr 14 '13 07:04

chenhongbin


2 Answers

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];
like image 192
Andrey Chernukha Avatar answered Sep 29 '22 01:09

Andrey Chernukha


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)
    }

}
like image 44
Rob Norback Avatar answered Sep 29 '22 00:09

Rob Norback