iOS device does not react when it is in correct position when using UIDeviceOrientationDidChangeNotification

StackOverflow https://stackoverflow.com/questions/14167957

  •  13-01-2022
  •  | 
  •  

質問

I have an app where I am making my iOS device make a sound when the user changes the device's position. I have the user put the device in a flat position, landscape position, and then portrait position, and when the user puts the device in those positions at the appropriate time, the app emits a sound to confirm the position.

My problem however is that if the device is initially in the flat position (e.g. lying flat on a desk), the device does NOT make a sound. In other words, the sound is only emitted when the user PUTS the device in that position and does not immediately sense the position that it is in already. Is there a way for me to rectify this such that the app emits a sound if it is either initially in that position or is put into the correct position? Here is my relevant code:

- (void) orientationCheck {

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(orientationChanged:)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:[UIDevice currentDevice]];

    timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(showTextOnly) userInfo:nil repeats:NO];
}


- (void) orientationChanged:(NSNotification *)note
{
    UIDevice *device = note.object;

    if(currentTest == flatTest) {

        testLabel.frame = CGRectMake(50, 30, 200, 150);
        [testLabel setText:@"Hold device on its side."];
        testImage.frame = CGRectMake(10, 150, 300, 200);
        testImage.image = [UIImage imageNamed:@"accelerometer test - side.png"];

        if (device.orientation == UIDeviceOrientationFaceUp || device.orientation == UIDeviceOrientationFaceDown) {

           ...

        }

    }

Can anyone see what I am doing wrong, and how I can fix this?

役に立ちましたか?

解決

Why don't you just check the device's orientation at launch time? In other words, besides registering for the notification when the device orientation changes, look to see what the device orientation is.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top