19

I'm trying to create a video player for my Swift app, but I keep getting the error of 'unresolved identifier AVPlayerViewController'. What am I missing?

I'm a beginner at this, I may have to ask a few thousand times in layman's terms. I've been scouring the internet for perhaps a day now for a video for how to embed a Youtube video into my app, with no results. If you could point me over to a tutorial that would be awesome!

Thanks!

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Dandelyons
  • 303
  • 1
  • 2
  • 5
  • 1
    Did you `import AVKit` at the top of your file? – dan Oct 16 '15 at 21:19
  • Just added that in, the original error message is gone, replaced by 'Cannot invoke initializer for type 'AVPlayerViewController' with an argument list of type '(contentURL:NSURL)' and 'Use of unresolved identifier'AVPlayerViewControllerStyleNone' – Dandelyons Oct 16 '15 at 21:24
  • Also, how do I add MediaPlayer Framework? – Dandelyons Oct 16 '15 at 21:30
  • You can't create an `AVPlayerViewController` with a URL. You create an `AVPlayer` with the URL and then set it as the `player` property on the controller. `AVPlayerViewControllerStyleNone` isn't a thing, what are you trying to do with that? `import MediaPlayer` to import the MediaPlayer framework. – dan Oct 16 '15 at 21:39
  • embed a Youtube you should use webview – Leo Dabus Oct 16 '15 at 21:43
  • I apologize @LeoDabus, but I'm not exactly sure how to do that...I experimented with it yesterday but I can't seem to get it to work. Is there a tutorial you know of? Thanks Again! – Dandelyons Oct 16 '15 at 23:13

7 Answers7

43

Xcode 8.2 • Swift 3.0.2

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var wv: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        loadYoutube(videoID: "oCm_lnoVf08")
    }
    func loadYoutube(videoID:String) {
        guard
            let youtubeURL = URL(string: "https://www.youtube.com/embed/\(videoID)")
            else { return }
        wv.loadRequest( URLRequest(url: youtubeURL) )
    }
}

Xcode 7.3.1 • Swift 2.x

import UIKit

class ViewController: UIViewController {
    // create an outlet for your webview 
    @IBOutlet weak var wv: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // load your you tube video ID
        loadYoutube(videoID: "oCm_lnoVf08")
    }
    func loadYoutube(videoID videoID:String) {
        // create a custom youtubeURL with the video ID
        guard
            let youtubeURL = NSURL(string: "https://www.youtube.com/embed/\(videoID)")
            else { return }
        // load your web request
        wv.loadRequest( NSURLRequest(URL: youtubeURL) )
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • I want to open this link but my screen only white not display any download file – Gaurav Patel Jul 08 '16 at 05:06
  • @GauravPatel Just create a new project and add that code there. I have just tested it here and it works fine Xcode 7.3.1 (AppStore version) – Leo Dabus Jul 08 '16 at 06:07
  • Im making sure i understand this correctly. You have to have a webview and call loadrequest on a NSURL request. right? – ahitt6345 Jul 31 '17 at 03:28
  • 1
    @LeoDabus i have used your webview code for playing youtube video. my url is `https://www.youtube.com/watch?v=_8aKKEjIO2g&feature=youtu.be` and when i load videoID `_8aKKEjIO2g` it say that `This video is unavailable`. why this happen do you know? – AbecedarioPoint Jul 25 '18 at 06:50
10

Swift 3/4

You can play youtube video in AVPlayer with the help of XCDYouTubeKit.

Add

pod 'XCDYouTubeKit'

into your project and write a code as below

func playVideo() {

        let playerViewController = AVPlayerViewController()
        self.present(playerViewController, animated: true, completion: nil)

        XCDYouTubeClient.default().getVideoWithIdentifier("KHIJmehK5OA") { (video: XCDYouTubeVideo?, error: Error?) in
            if let streamURL = video?.streamURLs[XCDYouTubeVideoQuality.HD720.rawValue] {
                playerViewController.player = AVPlayer(url: streamURL)
            } else {
                self.dismiss(animated: true, completion: nil)
            }
        }
    }

you can change the quality of video by replacing XCDYouTubeVideoQuality.HD720.rawValue with medium360 or with Small240

Chetan
  • 881
  • 14
  • 22
9

Use YouTube-Player-iOS-Helper:

Step 1: add pod "youtube-ios-player-helper", "~> x.y.z" to your Podfile, replace "x.y.z" with the latest version. and run pod install.

Step 2: Implement this code:

import UIKit
import youtube_ios_player_helper
 
class ViewController: UIViewController, YTPlayerViewDelegate {
    @IBOutlet weak var playerView: YTPlayerView!

    override func viewDidLoad() {
        super.viewDidLoad()
        playerView.delegate = self

        let playerVars = ["playsinline": 1] // 0: will play video in fullscreen
        self.playerView.loadWithVideoId("youtubeId", playerVars: playerVars)
    }     
}

Note: Set the rel key to 0 in your playerVars dictionary if you don't want to show related video:

let playerVars = ["playsinline":1, "rel" : 0 ]

javimuu
  • 1,829
  • 1
  • 18
  • 29
  • i have embeded `YTPlayerView ` but some video not playing. why this is happen any one know? – AbecedarioPoint Jul 25 '18 at 06:40
  • This pod is too old and haven't been updated. It stops working and no clue why it doesn't work. Don't use this pod anymore. – Raymond Jan 24 '20 at 23:47
  • I have used the mentioned pod. is there an option to hide the context menu. Also there is inconsistency in player controls. Some times its shows the Quicktime player controls and mostly the general YouTube controls – Nassif Nov 23 '21 at 03:58
1

I did by using below code on Swift 4+ version

guard let url = URL(string: "<Your YuTube url>")
        else{
            return
        }

let safariViewControllerObject = SFSafariViewController(url: url)
self.present(safariViewControllerObject, animated: true, completion: nil)

Note:- I have imported SafariServices lib

Prasanna
  • 945
  • 10
  • 24
1

Swift 4 for iOS12 you should import "WebKit" module

Make an outlet for WKWebView. Use following function, which you should call in viewDidLoad():

func getVideo(videoCode: String) {
    let url = URL(string: "https://www.youtube.com/embed/\(videoCode)")
    myWKWebView.load(URLRequest(url: url!))
}

For an argument videoCode in function getVideo, you should use the videoID, I will make it bulk on the example link below: https://www.youtube.com/watch?v=gI3pz7eFgfo&t=838s

0

Play youtube video in Swift 4.1

Add Pod pod 'XCDYouTubeKit'

import XCDYouTubeKit in ViewController

func playYoutubeVideo(){

    let strUrl = "https://www.youtube.com/watch?v=9m_K2Yg7wGQ"
    if let range = strUrl.range(of: "=") {
            let strIdentifier = strUrl.substring(from: range.upperBound)
            print("Identifier:\(strIdentifier)")
            let videoPlayerViewController = 
            XCDYouTubeVideoPlayerViewController(videoIdentifier: strIdentifier)
            videoPlayerViewController.present(in: viewYTVideo)
            videoPlayerViewController.moviePlayer.play()
        }
}
Community
  • 1
  • 1
  • 4
    Note that XCDYouTubeKit readme (https://github.com/0xced/XCDYouTubeKit) says that "XCDYouTubeKit is against the YouTube Terms of Service. The only official way of playing a YouTube video inside an app is with a web view and the iframe player API." – Hemaolle Nov 18 '18 at 07:20
0
import WebKit
import SnapKit

class YoutubeVideoView: UIView {
    
    private lazy var webConfig: WKWebViewConfiguration = {
        $0.allowsInlineMediaPlayback = true
        return $0
    }(WKWebViewConfiguration())
    
    private lazy var webView: WKWebView = {
        $0.scrollView.isScrollEnabled = false
        return $0
    }(WKWebView(frame: .zero, configuration: webConfig))

    private var url: String
    
    init(url: String) {
        self.url = url
        super.init(frame: .zero)
        configureViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func configureViews() {
        addSubview(webView)
        webView.snp.makeConstraints({ $0.edges.equalToSuperview() })
    }
    
    func play() {
        guard let url = URL(string: url) else { return }
        webView.load(.init(url: url))
    }
}