Hello, everyone here is a new and exciting article on how you can play youtube videos in swift.
We all need to implement the video player in our project at some point in app development.
Sometimes, we need to integrate the functionality to play the youtube links in a video player.
Here is the article that will allow you to embed the video player that plays the youtube videos.
So let’s begin with the article.
Adding assets
Firstly, we need to add the required asset which is adding a third-party library via Cocoapods.
Navigate to the project directory in the terminal and run the below commands.
- pod init
- open podfile
Podfile will open in the Text editor then add pod ‘YoutubePlayer-in-WKWebView’, “~> 0.2.0”
Do not forget to save the file.
Now run the pod install command on the terminal, this will install the third-party library which will be used to play youtube video links in the project.
Adding the code to play youtube videos in swift
Firstly, import the library in your swift file like import YoutubePlayer_in_WKWebView
You will need a youtube video link to play in the player.
After that, in the storyboard add a UIView that will be used to show the player, please check the below image.
In addition, assign the WKYTPlayerView class to the UIView and create an outlet in your swift file.
Getting Youtube Id
Now we will need the Youtube ID from the youtube video link to play the video.
We have created an extension to get the youtube id from the link, check the below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
extension String { var youtubeID: String? { let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)" let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) let range = NSRange(location: 0, length: count) guard let result = regex?.firstMatch(in: self, range: range) else { return nil } return (self as NSString).substring(with: result.range) } } |
We can get the youtube id as below
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class ViewController: UIViewController, WKYTPlayerViewDelegate { var youtubeId = "" @IBOutlet weak var player: WKYTPlayerView! var youtubeUrl = "https://www.youtube.com/watch?v=WnSSvz9ry_w&ab_channel=Webkul" override func viewDidLoad() { super.viewDidLoad() self.youtubeId = youtubeUrl.youtubeID ?? "" print("YoutubeId is: \(self.youtubeId)") } } |
Play Youtube video in swift
It’s time to play the video in the player view that we have created. Let’s write the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import UIKit import YoutubePlayer_in_WKWebView import AVKit class ViewController: UIViewController, WKYTPlayerViewDelegate { var youtubeId = "" @IBOutlet weak var player: WKYTPlayerView! var youtubeUrl = "https://www.youtube.com/watch?v=WnSSvz9ry_w&ab_channel=Webkul" override func viewDidLoad() { super.viewDidLoad() self.youtubeId = youtubeUrl.youtubeID ?? "" print("YoutubeId is: \(self.youtubeId)") player.load(withVideoId: self.youtubeId, playerVars: ["playsinline":"0"]) player.delegate = self } func playerViewDidBecomeReady(_ playerView: WKYTPlayerView) { player.playVideo() } override func viewDidDisappear(_ animated: Bool) { player.stopVideo() } } |
We provide the youtube Id extracted earlier to the player, the load function of the player loads the youtube video with the given youtube id.
playerViewDidBecomeReady function is used to play the video.
In viewDidDisappear we are stopping the player if the user dismisses the view.
Cheers!! Now the video will play in the player.
Getting information from the video link
Our main objective which is to play the youtube link has been completed.
In this section, we will know how to get the title of the video.
Below is the function used to get the title of the video link through the video id.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
func getVideoTitle(id: String) { let session = URLSession.shared let api = "https://www.googleapis.com/youtube/v3/videos?id=\(id)&key=AIzaSyBkH-qoGYyuHEwdSBsu0WxY8Ofj6tTuAjU&part=snippet" let url = URL(string: api) Alamofire.request(api).validate().responseJSON { response in switch response.result { case .success: let responseJson = response.result.value! as! NSDictionary print(responseJson) if let results = responseJson.object(forKey: "items")! as? [NSDictionary] { print(results) if results.count > 0 { print(results) if let snippet = results[0]["snippet"] as? NSDictionary{ print(snippet) DispatchQueue.main.async { self.nameLabel.text = snippet["title"] as? String ?? "" // assign the title to the label } } } } case .failure(let error): print(error) } } } |
Above all, we are using google API with the video id appended on the URL and hitting the API with Alamofire.
This gives us the JSON response and we extract the video title from the response and assign it to the label.
Conclusion
In this, article we learned to play the youtube video link in the swift project using the third-party library.
We have discussed how to get the title of the youtube video similarly, we can get the thumbnail from the video id.
That’s all for this article, we hope you enjoyed learning new things.
For more information please go through the link
For other blogs please click here