Embed youTube video in iOS Swift 4.2
Here we will learn how to embed youtube video in iOS swift 4.2.
We will get 2 types of url of a video, for example I am taking url of Oscar winning song ‘Jai Ho’
1. From address bar: https://www.youtube.com/watch?v=xwwAVRyNmgQ
2. From video screen: https://youtu.be/xwwAVRyNmgQ
In above both url’s we can find ‘xwwAVRyNmgQ’ this is unique with is nothing but youtube video ID.
We just have give this ID in the following url in place of ‘videoID’
“https://www.youtube.com/embed/\(videoID)"
and play the url in webView, that it!
Lets Code
Get videoID from url:
let url = “https://www.youtube.com/watch?v=xwwAVRyNmgQ"
1. Function way: we will simply write code in function which give us videoID
//Get video IDlet img = createThumbnailOfVideoFromRemoteUrl(url: "http://techslides.com/demos/sample-videos/small.mp4")do {let regex = try NSRegularExpression(pattern: "(?<=v(=|/))([-a-zA-Z0-9_]+)|(?<=youtu.be/)([-a-zA-Z0-9_]+)", options: .caseInsensitive)let match = regex.firstMatch(in: url, options: .reportProgress, range: NSMakeRange(0, url.lengthOfBytes(using: String.Encoding.utf8)))let range = match?.range(at: 0)let youTubeID = (url as NSString).substring(with: range!)} catch {print(error)}
2. Extension way: to make code more readable and reusable we use extensions
var videoID = url.youtubeIDextension 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)
}}
Play youtube video:
To play youtube video we have to take help of webView and load URLRequest like this:
func loadYoutube(videoID:String) {
guard let youtubeURL = URL(string: "https://www.youtube.com/embed/\(videoID)") else {
return
}
webView.load(URLRequest(url: youtubeURL))}
AVPlayer can’t support for youtube embed videos, if you want to play other video urls than here is the code:
let player = AVPlayer(url: URL(string: "http://techslides.com/demos/sample-videos/small.mp4")!)let vc = AVPlayerViewController()
vc.player = player
present(vc, animated: true) {
vc.player?.play()
}
For using webView we have to import ‘WebKit’ and ‘AVKit’ framework to use AVPlayer.
To know more about iOS frameworks, please check this link
As per application requirement we have to show thumbnail of a video from url, we can achieve this in following ways:
//From YouTubeID
func genarateThumbnailFromYouTubeID(youTubeID: String) {let urlString = "http://img.youtube.com/vi/\(youTubeID)/1.jpg"let image = try! (UIImage(withContentsOfUrl: urlString))!}//From VideoUrl
func getThumbnailFromVideoUrl(urlString: String) {
DispatchQueue.global().async {
let asset = AVAsset(url: URL(string: urlString)!)let assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)assetImgGenerate.appliesPreferredTrackTransform = truelet time = CMTimeMake(value: 1, timescale: 20)let img = try? assetImgGenerate.copyCGImage(at: time, actualTime: nil)if img != nil {
let frameImg = UIImage(cgImage: img!)
DispatchQueue.main.async(execute: {
// assign your image to UIImageView on main thread
})
}
}}
you may have question why I used ‘1.jpg’ in this ‘genarateThumbnailFromYouTubeID’ function to get thumbnail image, please check this: https://gist.github.com/protrolium/8831763
Full source code available here: https://gist.github.com/vikaskore/780ccf2e5187937d6ae9d7bbdf9b1509
Thank you, Happy coding!