davidohayon669 / react-native-youtube

A <YouTube/> component for React Native.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

UNAUTHORIZED_OVERLAY Android bug

abbasfreestyle opened this issue · comments

Currently experiencing this issue on Android. iOS is working fine.

Running:
react native: 0.44
react-native-youtube: 1.0.0-alpha-4
Device: Galaxy Note 5 (real device)

I always get UNAUTHORIZED_OVERLAY error when playing the video inline, it just shows a black screen, no controls whatsoever.
If the video starts as fullscreen it works perfectly fine, as soon as it goes inline it complains.

I've used previous version on RN 0.39 and it all works fine, my coding appears to be fine too. It seems to be a bug with RN 0.44.

<YouTube videoId={videoId} play={true}
           fullscreen={false} loop={false}
           controls={1}
           onReady={(e)=>{this.setState({ready:true})}}
           apiKey={apiKey}
           style={{width:300, height:150}}
           onError={(e) => {this.YTerror(e)}}
/>

Any solutions?

Same error using the branch v1. Just work when rotate the device.

RN: 0.44.0
react-native-youtube: 1.0.0-alpha.3

Has anyone found a solution to this? The rotating works for me, but it's not necessarily what I'd call preferable. 😅

I gave up to be honest, tried to remove <Text> in Youtube.android.js, because it seems to absolutely positioned, but it didn't solved an issue. There is also a comment here, but it doesn't seem to protect us anymore :) I even tried to inspect native Android UI hierarchy, and haven't found any view that is obviously covering the player, though in properties it says "overlayed" - true.
For now I've just embedded YT player in the WebView. As simple as this:

<WebView
  style={props.style}
  source={{uri: `https://www.youtube.com/embed/${props.videoId}?controls=0&showinfo=0`}}
/>

I know it's not a proper solution, but at least works on both iOS and Android with RN 0.44.3.
For iOS specifically it seems ridiculous to have react-native (which is kinda JS focused and encourages to unify the codebase) with the package, the adds native ObjC code, that creates webView with i-frame (which is JS-powered as well in that .html file that you have to include), just to expose that callbacks back to your JS...Ta-daaah!..I mean in RN it's rather easier to directly create i-frame right in WebView, and map the callbacks back if you really need them, with pure JS. There was a suggestion somewhere in the other Issues for this package to make a solution with WebView, I hope it will see the world someday :) But for simple "just play YT videos" use-case -
WebView + embed link as above would solve the problem.

The problem with this issue seems to be the status bar. I'm using react-native-navigation that supposedly allows you to hide the SB but its not working.

Anyone found any other solution yet?

Ok I actually was able to hide the status bar using StatusBar from react-native, but the problem persists, still same error

I think I might have found the reason for this error. I was running logcat and found this log that actually gave me a hint. So what I did was I just subtracted '2px' width from YouTube player and voila!!! Its working perfectly.

I am actually using react-native-drawer and inLine mode was not working at all.

screen shot 2017-06-11 at 11 51 55 pm

@reyhaan Where you subtract the px? I tried directly in the styles and doesn't work.

I discover that Youtube view will show when change the orientation of screen, and no need to set fullscreen nor play.

So I solved this problem by change a bit of the height in the styles after onReady event be triggered.
(initial height is 301)

onReady={e => this.setState({ height: 300 })}
style={{ alignSelf: 'stretch', height: this.state.height, backgroundColor: 'black', marginVertical: 10 }}

I run the example app as it is now and that one works, then I upgraded to the latest RN version, without doing any other change and then it stops working throwing that error. How could the height be different only by changing RN version?

Also I did a logcat and for me this is the error I'm getting

YouTubeAndroidPlayerAPI: YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is obscured by com.facebook.react.views.text.ReactTextView{77856fa V.ED..... ........ 0,40-28,116 #6}. Right edge 26 px right of YouTubePlayerView's left edge. Top edge 1158 px above YouTubePlayerView's bottom edge. .

I removed all the components from RCTYouTubeExample and just left the YouTube component

EDIT:

Now I get a similar error if I don't change the height onReady

YouTubeAndroidPlayerAPI: YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is not contained inside its ancestor android.widget.FrameLayout{dda59cb V.E...... ......I. 0,0-0,0}. The distances between the ancestor's edges and that of the YouTubePlayerView is: left: 0, top: 0, right: 0, bottom: 0 (these should all be positive).

Thank you @ben54260 !

This solved the problem, the videos are loading as expected and can toggle fullscreen with no issues. Strange why we need to do this, Android Youtube is a diva.

Closing

@abbasfreestyle The Android module really is pretty sensitive

@abbasfreestyle How's this solved? I just tried what @ben54260 said in the example project running on RN 0.45 and I still have the same issue. Did you change anything else other than that? What version of RN are you using? Have you tried running the example?

@tafelito can you try making those value 1 i.e. top:1, bottom: 1, right:1, left: 1 ? I am just guessing though!

@reyhaan Same thing. It gives the error

YouTubeAndroidPlayerAPI: YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is obscured by com.facebook.react.views.text.ReactTextView{312038a V.ED..... ........ 0,40-28,116 #6}. Right edge 26 px right of YouTubePlayerView's left edge. Top edge 1158 px above YouTubePlayerView's bottom edge. .

Not sure why it complains about a ReactTextView, cause I removed any extra view other than the YouTube player

Ok I found the issue. On the YouTube.android.js there is a TextView. I removed it and now it's working. Seems like that is not needed anymore, unless I'm missing anything

commented

According to youtube SDK website:

It is not permitted to overlay this fragment's view with other views while a video is playing.

This rule make me crazy, too. =(

@tafelito There seems to be some change that cause a bug in Android on RN > 0.44
I already solved it and will probably push the next few days

thanks @davidohayon669 that would be great!

@davidohayon669 did you manage to push it already? It's kinda killing purpose of the app I'm creating at the moment 😛

@davidohayon669 - unfortunately, problem persists.
If this can help that's the output from logcat:

06-25 17:35:33.725 16783-16783/com.vloggerapp W/YouTubeAndroidPlayerAPI: YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is obscured by com.facebook.react.views.view.ReactViewGroup{da778f3 V.E...... ........ 0,0-1080,1936 #22}. YouTubePlayerView is completely covered, with the distance in px between each edge of the obscuring view and the YouTubePlayerView being: left: 1, top: 319, right: 1, bottom: 929..

@DeviousM are you sure it isn't covered in any way? what do you get when you try the example in this repo?

@davidohayon669 I've been following this issue as it unfolds and also am having the same trouble.
If you need more information I hope I could help at least a little bit.

Project is using nativebase layouts (Container as a main wrapper for each component). Video loads up fine and plays for half a second then immediately stops with the overlay error. Also i have installed and relinked the latest version (alpha 6) and am on RN v44). Project is also using react-native-router-flux with a drawer component but I wouldn't imagine that causing any issues.

This problem persists on both emulator && physical device

YouTubePlayerView is completely covered, with the distance in px between each edge of the obscuring view and the YouTubePlayerView being: left: 1, top: 789, right: 293, bottom: 15

screen shot 2017-06-25 at 4 12 38 pm

code

return (
            <View style={styles.playerContainer}>
              <YouTube
                ref="youtubePlayer"
                videoId={song.songInfo.fkid}
                play={true}
                rel={false}
                fullscreen={false}
                showFullscreenButton={true}
                showinfo={false}
                controls={0}
                apiKey={myKey}
                origin={"https://www.youtube.com"}
                style={styles.youtube}
              />
            </View>
          );

styles.playerContainer = { 
    alignItems: "center",
    justifyContent: "center",
    marginTop: 300,
    marginLeft: 50
  }
styles.youtube= {
    alignSelf: "stretch",
    height: 300,
    width: 300
}

Edit1: trying a bunch of different configurations and it seems like it's got something to do with a view much higher up in the tree. RCTView is super fucky with it

@chrissbendel - I have exactly the same issue. Also using the NativeBase & react-native-router-flux & drawer component. Don't know if it has anything to do with it.

@DeviousM i was spending the entire day yesterday ripping my hair out in frustration. Seems like even loading JUST the youtube player with no other views/containers on top of it inside of a nested scene I get the overlay error with JUST ~150px for the top of the youtubeplayer container, but when i try to either move the player down with margin top, margin vertical, padding, or anything else, then the left, right, and bottom margin errors come in with totally random numbers (like 566px for the bottom, 27 px left and right).

Router and scene config looks like this for anyone interested. I'm wondering if it has to do with router flux and possibly the drawer.

Removing the wrapping Container also doesn't do anything at all for the youtube player. I am attempting to put the youtube player inside of the room component, so the only scenes wrapping it are main -> drawer -> root

<Container>
        <Router>
          <Scene key="main" type="reset">
            <Scene key="drawer" open={false} ee={ee} component={DrawerNav}>
              <Scene key="root" tabs={false} drawerIcon={<Icon name="menu" />}>
                <Scene
                  key="Lobby"
                  ee={ee}
                  component={Lobby}
                  title="Lobby"
                  renderRightButton={() => {
                    if (this.state.room) {
                      return (
                        <TouchableOpacity
                          onPress={() => {
                            Actions.Room({
                              room: this.state.room,
                              title: this.state.room.name,
                              old: true
                            });
                          }}
                        >
                          <Icon name="musical-notes" />
                        </TouchableOpacity>
                      );
                    }
                  }}
                />
                <Scene key="Room" ee={ee} component={Room} title="Room" />
                <Scene
                  key="Messages"
                  ee={ee}
                  component={PrivateMessages}
                  title="Messages"
                />
                <Scene
                  key="Conversation"
                  ee={ee}
                  component={Conversation}
                  title="Conversation"
                />
                <Scene key="Login" ee={ee} component={Login} title="Log In" />
              </Scene>
            </Scene>
          </Scene>
        </Router>
      </Container>

I can confirm this is being caused by the wrapping drawer component @DeviousM . After removing the drawer seems that things work just fine... now to figure out how to integrate it without it causing issues

Hey @DeviousM , I think i've found a solution (this bug doesn't seem to be on the react-native-youtube lib, but rather with the wrapping drawer). If we have a similar setup (with a drawer wrapping the entire content of the app and all nested scenes), try doing something like this to your tweenHandler prop in the Drawer (assuming you're using react-native-drawer).

The key thing that got it working for me was setting mainOverlay: width: 0. It seems as if the default main overlay of the drawer is covering the entire screen, so setting this to 0 seems to keep everything else working as is and not affect the video overlay. Definitely let me know if this workaround works for you too, thanks!

    return (
      <Drawer
        ref={ref => (this._drawer = ref)}
        open={state.open}
        type="displace"
        content={SideMenu}
        tapToClose={true}
        openDrawerOffset={0.5}
        panOpenMask={0.2}
        panCloseMask={0.4}
        panThreshold={0.5}
        negotiatePan={true}
        // tweenHandler={Drawer.tweenPresets.parallax}
        tweenHandler={ratio => ({
          main: { opacity: Math.max(0.54, 1 - ratio) },
          mainOverlay: { width: 0 }
        })}
      >
        <DefaultRenderer
          navigationState={children[0]}
          onNavigate={this.props.onNavigate}
        />
      </Drawer>
    );

@davidohayon669 I just tried the example app with the alpha.6 and it's working fine for me.
But I tried it within my app that uses react-native-navigation and it's not working. I'm trying to figure it out what the issue could be.

Thanks for the update anyway

Exactly the same with me. It worked for me on the deprecated navigation. But It doesnt work with react-native-navigation

Yeah and this is the error is giving

YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is obscured by com.reactnativenavigation.views.SnackbarAndFabContainer{80e301 V.E...... ........ 0,0-1440,2464}. YouTubePlayerView is completely covered, with the distance in px between each edge of the obscuring view and the YouTubePlayerView being: left: 2, top: 419, right: 2, bottom: 1239..

I'm trying to find a way to solve this

@davidohayon669 Any ideas?

@tafelito @abbasfreestyle you must think of any view that might be blocking the youtube view or even just too close to it. If the example in the repo works for you than the problem must be in your app's view heirarchy

@davidohayon669 I think the problem with react-native-navigation and probably other navigation libraries that uses the same logic, is that all the content is put inside a parent layout, where then you get access to the FAB or the snackbar or even the drawer. So the relative layout that the player uses, ends up within the main layout, hence it complains being covered.

I'm not completely sure about the internals of react-navigation because I haven't used it yet, but I'll give it a try and see how it goes.

This not working, even using the sample example. I was never able to get the video running (One sec then it pauses again) giving UNAUTHORIZED_OVERLAY
I took out all other components, nothing else except the Youtube. Tried to adjust margins as well; but still same result.

@davidohayon669 going back to my examples and issues, it ended up working but then when I try to use any of the callback methods (onChange, onReady) to use the seekTo(time) method the error comes back (android). Could there be something happening under the hood where when we target the player by it's ref it changes the layout of the android youtube player? it works without trying seekto, but as soon as seekTo comes into the mix it gives the same unauthorized_overlay error

@chrissbendel @natour @tafelito I've tried to elaborate on the issue here with what I know so far. Please make an effort and try the example app so you can eliminate at least some causes before we discuss them here.

@davidohayon669 I tried the example app and it works fine for me. I also added react-navigation to the sample app and it also works ok.

As I said before, the problem seems to be having some of views or layouts on top of the RelativeLlayout that RNY uses. At least that's what I see it's happening with react-native-navigation

The difference is that RN it's a pure JS library, so I don't think there would any problem with it.

Ok I take back what I just said. It does work with react-navigation, but not always.

If I start the video below the NavBar, it plays fine. Then if I scroll while playing and the video ends up behind the NavBar, it stops, giving the same error.

Some screenshots

img_5705

img_5707

@tafelito This was always the same. The minute the player is covered it stops playing. It is unhackable AFAIK

you are right @davidohayon669, jus tested with an Android project using the native YouTubePlayer sdk and it does the same thing.

I test the example with react native navigation , problem persist.

@nimamyscreen gather as much relevant information you can

In logcat I get this warning when I push the screen by navigator

06-29 17:44:53.747 27195-27195/com.reduxtemplate W/YouTubeAndroidPlayerAPI: Forcefully created overlay:wjs@b2e6f2a helper:Lazy@d20511b view:null status: ...... {...}
06-29 17:44:56.117 27195-27195/com.reduxtemplate W/YouTubeAndroidPlayerAPI: YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is obscured by com.reactnativenavigation.views.SnackbarAndFabContainer{4d7fccf V.E...... ........ 0,0-1080,1680}. YouTubePlayerView is completely covered, with the distance in px between each edge of the obscuring view and the YouTubePlayerView being: left: 1, top: 345, right: 1, bottom: 729

when I try to open the youtube component inside a modal, the app completely crash and exit. I get this error in logcat

06-29 18:33:29.887 22196-22196/com.reduxtemplate W/ResourceType: No package identifier when getting name for resource number 0x000001f1
06-29 18:33:29.887 22196-22196/com.reduxtemplate D/AndroidRuntime: Shutting down VM
06-29 18:33:29.897 22196-22196/com.reduxtemplate E/AndroidRuntime: FATAL EXCEPTION: main
                                                                   Process: com.reduxtemplate, PID: 22196
                                                                   android.content.res.Resources$NotFoundException: Unable to find resource ID #0x1f1
                                                                       at android.content.res.Resources.getResourceName(Resources.java:3749)
                                                                       at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:976)
                                                                       at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1164)
                                                                       at android.app.BackStackRecord.run(BackStackRecord.java:793)
                                                                       at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1557)
                                                                       at android.app.FragmentManagerImpl$1.run(FragmentManager.java:488)
                                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:148)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:7326)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

I even removed drawer but problem persist.

"dependencies": {
"axios": "^0.16.1",
"react": "16.0.0-alpha.6",
"react-native": "0.44.0",
"react-native-youtube": "^1.0.0-alpha.6",
"react-native-navigation": "^1.1.54",
"react-redux": "^5.0.4",
"redux": "^3.6.0",
"redux-thunk": "^2.2.0"
},

@nimamyscreen try delaying the mounting of the <YouTube /> to after the navigation ended. Maybe the animation of the navigation disrupts the native component.

I would try to find some event to attach to, or just try 500-1000ms delay just to test if the problem got anything to do with the navigation event

FWIW, After trying the above to no avail, I removed all navigation by creating a single page with just the youtube component on it and I still get these errors. See my comment on #131
My belief is there is some bug in the underlying Android Native youtube player that will need to be addressed.

any update on this?

@karan101292 This issue is not fully addressable. There is no way to cover the native component without making the video stop. If you have any problem that you think shouldn't occur please describe it more specifically

Same problem!
When some other view on top of "Youtube View", this may case "UNAUTHORIZED_OVERLAY ".
Youtube View needs to be on the top zIndex of the screen.
I reslove this bug : move the "Youtube View" to top of you views.

@abbasfreestyle "Youtube View" can not be blocked by other views

@zhouxuemeng1988

Could you explain what you mean by moving the youtube view to the top of your views?
When you say it needs to be at the top of the zIndex screen, is this involving position: 'absolute' ?

@abbasfreestyle
I find youtube api.
https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubePlayer.ErrorReason

YouTubePlayer.ErrorReason.UNAUTHORIZED_OVERLAY | Playback has been stopped due to a view overlaying the player.

For those of you who ( @nimamyscreen ) are using react-native-navigation and seeing the issue with overlay by com.reactnativenavigation.views.SnackbarAndFabContainer, if you are not using snackbar or fabs you can uncomment the line here and it works:

https://github.com/wix/react-native-navigation/blob/0f4e30ac33e1f9793aa5efd63019f75cb3ad49d5/android/app/src/main/java/com/reactnativenavigation/layouts/SingleScreenLayout.java#L65

Definitely a hack, will try to work out a maintainable solution for react-native-navigation

@matthiasleitner we tried your suggestion, but it seems that just commenting out

//createFabAndSnackbarContainer();

does not do the trick. There are dependencies on the parts inside this method. Do we miss something?

I've ran into a same problem, but with react-navigation. My components hierarchy is:
Drawer -> StackNavigator -> TabNavigator.
On one of the tab i render Youtube component, it works normally until i try to make it full-screen. The traceback from android studio is:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.myapp, PID: 2718
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp/com.myapp.MainActivity}: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.inprogress.reactnativeyoutube.VideoFragment: make sure class name exists, is public, and has an empty constructor that is public
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                      at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519)
                      at android.app.ActivityThread.-wrap19(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                   Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.inprogress.reactnativeyoutube.VideoFragment: make sure class name exists, is public, and has an empty constructor that is public
                      at android.app.Fragment.instantiate(Fragment.java:633)
                      at android.app.FragmentState.instantiate(Fragment.java:111)
                      at android.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1942)
                      at android.app.FragmentController.restoreAllState(FragmentController.java:135)
                      at android.app.Activity.onCreate(Activity.java:957)
                      at com.facebook.react.ReactActivity.onCreate(ReactActivity.java:53)
                      at android.app.Activity.performCreate(Activity.java:6679)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
                      at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519) 
                      at android.app.ActivityThread.-wrap19(ActivityThread.java) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:154) 
                      at android.app.ActivityThread.main(ActivityThread.java:6119) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
                   Caused by: java.lang.InstantiationException: java.lang.Class<com.inprogress.reactnativeyoutube.VideoFragment> has no zero argument constructor
                      at java.lang.Class.newInstance(Native Method)
                      at android.app.Fragment.instantiate(Fragment.java:622)
                      at android.app.FragmentState.instantiate(Fragment.java:111) 
                      at android.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1942) 
                      at android.app.FragmentController.restoreAllState(FragmentController.java:135) 
                      at android.app.Activity.onCreate(Activity.java:957) 
                      at com.facebook.react.ReactActivity.onCreate(ReactActivity.java:53) 
                      at android.app.Activity.performCreate(Activity.java:6679) 
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) 
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618) 
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
                      at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519) 
                      at android.app.ActivityThread.-wrap19(ActivityThread.java) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:154) 
                      at android.app.ActivityThread.main(ActivityThread.java:6119) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

UPDATE
I have tested the YouTubeStandaloneAndroid and it works perfectly with no crashes.

UPDATE
Ok, temporary fix is to use react-native-thumbnail-video to render only preview image of the video, and, after clicking on it launch Standalone player. For now code looks like this:

import { YouTubeStandaloneAndroid } from 'react-native-youtube';
import Thumbnail from 'react-native-thumbnail-video';

const API_KEY = '***';

class VideoTab extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: true
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.video.videoId !== this.props.video.videoId) {
      this.setState({ show: false });
    }
  }

  openPlayer = (videoId) => {
    YouTubeStandaloneAndroid.playVideo({
      apiKey: API_KEY,
      videoId,
      autoplay: true
    })
      .then(() => console.log('Player closed'))
      .catch(e => console.error(e));
  };

  render() {
    const { title, date, videoId } = this.props.video;
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.title}>{title}</Text>
          <Text style={styles.date}>{date}</Text>
        </View>
        {this.state.show &&
        <View style={styles.youtubeContainer}>
          <Thumbnail
            url={videoId}
            onPress={() => this.openPlayer(videoId)}
            imageHeight="100%"
          />
        </View>
        }
      </View>
    )
  }
}

Thanks @matthiasleitner. This is still not enough as the Youtube player detects an overlay. We will further investigate this issue.

Does anyone know if this problem persists if you setup the YouTube player api in webview?

commented

@GoaGit SnackbarAndFabContainer is used not only in SingleScreenLayout, but also in BottomTabsLayout. If your app is tab based, try commenting out everything related to snackbarAndFabContainer in BottomTabsLayout. That worked for me.

Thank you @Ilushkanama. We managed to solve this issue as well.

@matthiasleitner Your solution works with react-native-navigation.

Any solution using react-navigation and the YouTube component?

@LucasBassetti Have you got the same problem UNAUTHORIZED_OVERLAY ?

For anyone else working through this issue in conjunction with react-navigation:

I've created a bare bones app to demonstrate this issue at https://github.com/afestein/react-navigation-youtube-demo.

None of the combinations I've tried precisely replicate the "unauthorised overlay" error I'm seeing in my app, but they do demonstrate YouTube videos becoming unplayable when you switch tabs.

It has a few different branches:

master uses createBottomTabNavigator. This demonstrates the 'black' unplayable YouTube videos.

material-bottom-tabs uses the material bottom tabs. This is what I'm using in my React Native app and demonstrates the same behaviour as above.

with-stack-navigator uses a stack navigator. This branch seems to work perfectly fine when playing YouTube videos.

Hopefully this is a good starting point to try and troubleshoot this issue.

@matthiasleitner even though your solution solves the youtube issue, it makes app crash when you use react-native-navigation function popToRoot.

So a proper solution still needed...

Here is an unapproved pull request for react-native-navigation that solves the youtube overlay problem without crashing the app https://github.com/wix/react-native-navigation/pull/2165/files?utf8=%E2%9C%93&diff=split

@afestein Hello, Is there any news about youtube with react-navigation ?
I didn't manage to find an issue on the react-navigation github

Having the same overlay problem when I switch tab :-(

Same problem!
When some other view on top of "Youtube View", this may case "UNAUTHORIZED_OVERLAY ".
Youtube View needs to be on the top zIndex of the screen.
I reslove this bug : move the "Youtube View" to top of you views.

@abbasfreestyle "Youtube View" can not be blocked by other views

How You solved this is Issue? Can you explain it briefly? I was stuck at the same issue.

Here is an unapproved pull request for react-native-navigation that solves the youtube overlay problem without crashing the app https://github.com/wix/react-native-navigation/pull/2165/files?utf8=%E2%9C%93&diff=split

Hello @ziyafenn
I have used "react-native-navigation": "^2.0.2621" in my project.
and there is no any file found as you mentioned and any hack for V2.

hi @JaydeepJikadra,
i'm using v1 and unfortunately, i can't help you with v2.

same problem using react-navigation

RN 0.57.6
YT Player lasted verison

So we haven't found a solution to this? I'm going to file an issue with react-navigation and see wha they say. I'm on RN 59.2, react-navigation 3.3.2 and react-native-youtube 1.1.0

The issue is here in case any of y'all want to go over and comment/add your thoughts.

UPDATE: We found that it worked on Android at 2.18.2

commented

For me it wasn't working when I switched between tabs (react-navigation), so I created a switch navigator and I switch between the tabs through a bottom tab bar I created manually. It works!

Any solutions with react-native-navigation V2

@AyushAppin We found that it worked on Android at 2.18.2

@AyushAppin We found that it worked on Android at 2.18.2

I think you are talking about react-navigation rather than react-native-navigation. Let me check it on that version though.

@JaydeepJikadra Did you found any solutions for this issue?

This issue has been open for over 2 years, and this repo hasn't had a commit in over a year, so personally I'm looking at an alternative solution rendering YouTube videos through a <WebView> instead.

Furthermore, I tried using this library on a fresh install of the latest React Native (0.59.8) and I couldn't get it working at all (just a blank square appeared). I'm not sure if that was just a quirk in my setup but it's eroded my confidence further. (RN needs to be upgraded to 0.59 to satisfy the new Play Store 64-bit requirement after August 1).

I think this workaround for react-navigation is clever, but I really don't want to roll my own tab navigator.

commented

Same here error: "UNAUTHORIZED_OVERLAY".

"react": "16.8.3",
"react-native": "0.59.9",
"react-native-youtube": "^1.1.0",
"react-navigation": "^3.11.0",

Same here error: "UNAUTHORIZED_OVERLAY".

"react": "16.8.3",
"react-native": "0.59.9",
"react-native-youtube": "^1.1.0",
"react-navigation": "^3.11.0",

same result here using this setup too!

@rochapablo @brasrox

Apparently, this is a react-navigation issue, especially if you're using 'createBottomTabNavigator'.

I switched to "react-navigation": "2.18.2". Which in turn needed me to remove 'createAppContainer' call from my main nav setup and return my nav simply without the AppContainer. It worked!

Had the same problem when i changed from stackNavigatior to drawerNavigatior

EDIT:

I've found a workaround for my problem, i created a new stackNavigator inside the switchNavigator with the youtube player view and manually handled the navigation

const TutorialVideoStack = createStackNavigator({
	tutorialView: {
		screen: TutorialView,
		navigationOptions: ({ navigation }) => ({
			title: 'Tutorial',
			headerLeft: <BackArrow navigation={navigation} />,
			...navigationConstants,
		}),
	},
});

export default createAppContainer(
	createSwitchNavigator(
		{
			App: AppStack,
			Auth: AuthStack,
			Tutorial: TutorialVideoStack,
		},
		{
			initialRouteName: 'Auth',
		},
	),
);

For anyone who using this with react navigation, I got this problem gone, just by adding the screen on the most top / root of stacknavigator. the one that usually the value of createAppContainer parameter. 🍻

@ramazord do you have a code sample?

@ramazord example please :-)

For example if you have a file that use createAppContainer like this :

Example :

Homepage.js

import React from 'react';
import { View, Text } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';

class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
      </View>
    );
  }
}

const AppNavigator = createStackNavigator({
  Home: {
    screen: HomeScreen,
  },
});

export default createAppContainer(AppNavigator);

App.js

const AppContainer = createAppContainer(AppNavigator);

export default class App extends React.Component {
  render() {
    return <AppContainer />;
  }
}

And you have a component that have react-native-vdeo in it, lets call the component is <YoutubeVideo />

then modify the Homepage.js (the stackNavigator that putted into createAppContainer a.k.a the root), like this

Homepage.js

import React from 'react';
import { View, Text } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import YoutubeVideo from './YoutubeVideo';

class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
      </View>
    );
  }
}

const AppNavigator = createStackNavigator({
  Video: {
    screen: YoutubeVideo,
  },
  Home: {
    screen: HomeScreen,
  },
  //Dont put it here it will not resolve the UNAUTHORIZED_OVERLAY problem
});

export default createAppContainer(AppNavigator);

@marksturm @Tercera I'm sorry for the slow response i'm pretty hectic this week 😅😅😅

thanks :) but i found out, that it does not work with the drawernavigation ...

thanks :) but i found out, that it does not work with the drawernavigation ...

Yeah, sadly i can't find the solution for that 😓

In my case I have several createMaterialTopTabNavigator() and the same with createStackNavigator(). The problem wasn't navigation, was the "MenuProvider" set in "App".

This way it works:

AppNavigationContainer.tsx:

const MyOffersTabStack = createMaterialTopTabNavigator(
    {
        MisCuponesAhorroScreen,
        MisFavoritosScreen,
    },
    {
        tabBarPosition: 'top',
        initialRouteName: 'MisCuponesAhorroScreen',
        lazy: true,
        swipeEnabled: true,
        animationEnabled: true,
        navigationOptions: {
            header: null,
            mode: 'float',
        },
        tabBarComponent: MCMyOffersTabBar,
    }
);

const HomeTabStack = createMaterialTopTabNavigator(
    {
        HomeScreen,
        StoreScreen,
        MyOffersTabStack,
        MyShoppingListsScreen,
        ProfileScreen
    },
    {
        tabBarPosition: 'bottom',
        initialRouteName: 'HomeScreen',
        lazy: true,
        swipeEnabled: () => LoginUtils.isUserLogged(),
        animationEnabled: true,
        // @ts-ignore
        navigationOptions: ({navigation}) => ({
            tabBarVisible: tabbarVisible(navigation),
            header: null,
            mode: 'float'
        }),
        tabBarComponent: MCHomeTabBar,
    }
);

const MainStack = createStackNavigator(
    {
        MCSplashScreen,
        HomeTabStack,
        LoginScreen,
        RegisterScreen,
        StoresFinderScreen,
        ...,
        HelpScreen,
        YoutubePlayerScreen,
    },
    {
        initialRouteName: 'MCSplashScreen',
        headerMode: 'none',
        transitionConfig: () => Platform.OS === 'ios' ? fromRight() : fromBottom(),
    }
);

const AppStack = createStackNavigator(
    {
        Main: {
            screen: MainStack,
        },
        LoadingModal,
        AddExtraIdentificationModal,
        RecoverPasswordModal,
        ...,
        MCAddProductFilterModal,
    },
    {
        mode: 'modal',
        headerMode: 'none',
        transparentCard: true,
        initialRouteName: 'Main',
        navigationOptions: {
            swipeEnabled: false,
        },
        transitionConfig: () => fadeIn(),
    }
);

/**
 * Exporting the AppNavigationContainer of the App.
 * Will be exposed all the available screens and modals.
 */
export default createAppContainer(AppStack);

and the App.tsx:

public render() {
        return (
            {/*<MenuProvider> THIS was the problem (move to the screen that really needs it)*/ }
            <View style={{flex: 1}}> 
                <StatusBar barStyle={'dark-content'} translucent backgroundColor={Colors.TRANSPARENT} />
                <Provider store={App.APP_STORE}>
                    <View style={{flex: 1, backgroundColor: Colors.WHITE_FAFAFA}}>
                        <AppNavigationContainer ref={(view: any) => NAV_REF = view} />
                    </View>
                </Provider>
            </View>
            {/*</ MenuProvider> THIS was the problem */ }
        );
    }

and YoutubePlayerScreen.tsx:

import React from 'react';
import {IScreenDefaultProps} from '../../utils/GenericUtils';
import Config from 'react-native-config';
import YouTube from 'react-native-youtube';
import {StatusBar} from 'react-native';

interface IYoutubePlayerScreenArgs {
    url: string;
}

export default class YoutubePlayerScreen extends React.Component<IScreenDefaultProps<IYoutubePlayerScreenArgs>> {

    public componentDidMount(): void {
        StatusBar.setHidden(true);
    }

    public componentWillUnmount(): void {
        StatusBar.setHidden(false);
    }

    public render() {
        const splitUrl = this.props.navigation.getParam('url', '').split('/');
        const videoId = splitUrl[splitUrl.length - 1];

        return (
            <YouTube
                play
                videoId={videoId}
                showinfo={false}
                modestbranding
                showFullscreenButton={false}
                onReady={e => console.log('onReady', e)}
                onChangeState={e => console.log('onChangeState', e)}
                onChangeQuality={e => console.log('onChangeQuality', e)}
                onError={e => console.log('onError', e)}
                style={{width: '100%', height: '100%'}}
                apiKey={Config.ANDROID_API_KEY}
            />
        )
    }
}

With this configuration, the YoutubePlayerScreen.tsx works correctly. Hope someone helps!

commented

Ok I found the issue. On the YouTube.android.js there is a TextView. I removed it and now it's working. Seems like that is not needed anymore, unless I'm missing anything

I'm not found "TextView" in YouTube.android.js . I Found Text but it not use in this file
Screenshot 2019-10-17 at 12 19 26 PM

Working Here!!.
Well. there is some view over the youtube player when i use react-navigation. And my video paused due to UNAUTHORIZED_OVERLAY Android bug.

react-navigation@4.0.10
react-navigation-drawer@2.3.1
react-navigation-stack@1.10.2
react@16.8.3
react-native@0.59.10
react-native-safe-area-context@0.5.0
react-native-safe-area-view@1.0.0
react-native-youtube@2.0.0
react-native-responsive-screen@1.3.0

So i used react-native-safe-area-context and react-native-safe-area-view to wrap my whole App including react-navigation to avoid any screen edges.

import React, { Component } from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import SafeAreaView from 'react-native-safe-area-view';
import MyWholeApp from './App';
class AppContainer extends Component {
  render() {
    return (
      <SafeAreaProvider>
        <SafeAreaView forceInset={{ top: 'always' }} style={{ flex: 1 }}>
         <MyWholeApp/>
        </SafeAreaView>
     <SafeAreaProvider>)}
     }

And in one of screen of Stack Navigation
used react-native-youtube in render method as this:

import React, { Component } from 'react';
import {widthPercentageToDP, heightPercentageToDP} from 'react-native-responsive-screen';
class UtubeScreen extends Component {
  render() {
    return (
              <View
              style={{
                  width: widthPercentageToDP(100),
                  height: heightPercentageToDP(100) 
                      }}>
                  <View
                   style={{
                  width: widthPercentageToDP(100),
                  height: heightPercentageToDP(30) ,
                  backgroundColor: '#222'
                      }}>
                 <YouTube
                 ref={this._youTubeRef}
                 apiKey={'YOUR_API_KEY'}
                 videoId={'98LoiMZ59Jw'}
                 play={true}
                 fullscreen={false}
                 showFullscreenButton={true}
                 style={{width: widthPercentageToDP(100),height: heightPercentageToDP(30)}}
                 onProgress={({ currentTime }) => {
                 this.setState({ currentTime });
                 }}
                 modestbranding={true}
                 rel={false}
                 showinfo={false}
                />
          </View>
    </View>)}
     }

This code is working for me.

const [iscontainerMounted, setIsContainerMounted] = useState(false);
const [containerWidth, setContainerWidth] = useState();

<View
	style={{
	  flex: 1,
	}}
	onLayout={({
	  nativeEvent: {
		layout: { width },
	  },
	}) => {
	  if (!iscontainerMounted) setIsContainerMounted(true);
	  if (containerWidth !== width) setContainerWidth(width);
	}}
	>
	{iscontainerMounted && (
	  <YouTube
		apiKey={constants.YT_KEY}
		videoId={videoData.id.videoId}
		play
		style={{
		  alignSelf: 'stretch',
		  height: PixelRatio.roundToNearestPixel(containerWidth / (16 / 9)),
		}}
	  />
	)}
</View>

Any update on this issue?

any update on this issue

I managed to make this work. Just make sure the view with youtube is not hidden or covered by another view AND the height of the component is properly set. So, I put padding in the wrapper view as following:

<View style={{
    height: (Dimensions.get("window").width * (9/16)) + 20 , 
    paddingVertical: 10
}}>
     <YouTube 
          apiKey="key"
          videoId={"id"}
          play 
          loop 
          style={{ alignSelf: 'stretch', height: (Dimensions.get("window").width * (9/16)) }}
          controls={1}
      />
</View>

if i remove createDrawerNavigator then it works. (Video will play properly in android with RN-0.61.2, react-navigation 3.11.1)
but its not solution. can any one help me.

finally!! I am giving up, i removed this module and used react-native-thumbnail-video. now no problem for me

Any updates???

I found a fix. You should never render more than one YouTube component at the same time. Render one Youtube component for the currently playing video, and for the other videos just render a thumbnail using an Image component.

@OmarBasem Well, it is written in the single documentation page of this library