Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: Allow device rotation only when webview plays video

My current working app is locked in portrait mode through entire screens. The app plays embedded YouTube videos on webview and I just want to allow the landscape mode only when it plays in full screen.

I see there are some tricks for native ways and I think there aren't compatible with React Native. I also checked react-native-orientation but it doesn't help me.

Is there a simple and clean way I can implement this?

like image 261
Oscar Avatar asked Mar 04 '17 14:03

Oscar


1 Answers

I may be a little late to the party but I've recently added what your question is requesting.

Our goal

The application should be fixed to a portrait orientation, unless a User is watching a video. When watching a video, Users should be able to freely switch between portrait and landscape.

Getting Started

I'll outline how I did it in iOS, the React Native part certainly works on Android too.

Enable ALL orientations

You wan't to enable all orientations (Portrait, Upside Down, Landscape Left, Landscape Right).

I've taken the following image from Google, just ensure all checkboxes are ticked.

enter image description here

React Native Package

Download react-native-orientation and inside of your index.ios.js, add the code to lock the device orientation.

For example, mine's inside a componentWillMount.

componentWillMount() {
  Orientation.lockToPortrait();
}

Disable lock when watching a Video via a WebView

I then have a simple VideoPlayer component.

<TouchableWithoutFeedback onPress={this.handleClick}>
  <WebView
    source={{uri: 'https://youtube.com'}}
  />
</TouchableWithoutFeedback>

I used TouchableWithoutFeedback as I don't want the User to know that they've clicked something.

Create a handleClick function:

handleClick = () => {
  Orientation.unlockAllOrientations()
}

The tricky bit, and it's hacky!

I couldn't find a way to tell when the User had finished watching a Video within a WebView. This is because iOS uses its native player.

My VideoPlayer component is within a ScrollView (amongst other components). When the User scrolls (after watching a video), the application will again lock back to a portrait orientation.

<ScrollView
  onScroll={() => { Orientation.lockToPortrait(); }}
/>

Note

This will lock on all devices, including Tablets. If you want to only run it on a phone, I use react-native-device-info to detect whether the device is a tablet or not.

You could wrap all your orientations within an if statement:

if (!DeviceInfo.isTablet()) {
  Orientation.lockToPortrait();
}
like image 137
Dan Avatar answered Sep 16 '22 13:09

Dan