iOS: how to instantiate YTPlayerView programmatically?

235 views Asked by At

I'm trying to instantiate the YTPlayerView from the youtube_ios_player_helper pod programmatically, with the following code:

let player = YTPlayerView()
   player.cueVideo(byId: "someId", startSeconds: 0)

then the needed constraints are created and the youtubeplayer view is added to the containerview.

But, the internal webview, remains for ever nil, and is not created. I suppose I'm not instantiating the player correctly, but I did not found any information about how to do it.

Any Help?

thanks

2

There are 2 answers

0
Bill On BEST ANSWER

If you look at the source code, cueVideoById does not actually create the internal webview, you need to first call one of the following:

- (BOOL)loadWithVideoId:(NSString *)videoId
- (BOOL)loadWithPlaylistId:(NSString *)playlistId
- (BOOL)loadWithVideoId:(NSString *)videoId playerVars:(NSDictionary *)playerVars
- (BOOL)loadWithPlaylistId:(NSString *)playlistId playerVars:(NSDictionary *)playerVars
0
Glenn Posadas On

You must be creating an object player of YTPlayerView, BUT, it gets deallocated easily. So what to do? Make that a property. Something like this:

private lazy var player: YTPlayerView = {
    return YTPlayerView()
}()

override func viewDidLoad()...

or

private var player: YTPlayerView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.player = YTPlayerView()
}