To play Youtube Video in iOS app
Here's another solution if you don't want to use the API provided by YouTube and instead continue using a UIWebView
.
YouTube has functionality to load any video in fullscreen in a webview without any of the scrolling features using a URL in the format https://www.youtube.com/embed/<videoId>
.
For example, to load Gangnam Style using this method, simply direct the UIWebView to the URL https://www.youtube.com/embed/9bZkp7q19f0.
The API that YouTube provides to embed videos in iOS apps is indeed written in Objective-C, but it works just as well in Swift.
To install the library via CocoaPods, follow the CocoaPods setup instructions and add the following line to your Podfile:
pod ‘youtube-ios-player-helper’, ‘~> 0.1’
Once you have run pod install
, be sure to use the .xcworkspace
file from now on in Xcode.
To import the pod, simply use the following import statement at the top of your Swift files:
import youtube_ios_player_helper
You can then create youtube player views as follows:
let playerView = YTPlayerView()
You can include this view in your layouts as you would any other UIView. In addition, it includes all of the functions listed in the YouTube documentation. For instance, to load and play a video, use the following function:
playerView.load(withVideoId: videoId);
Where videoId
is the string id found in the URL of the video, such as "9bZkp7q19f0"
.