Search code examples
iosswiftvideouiwebviewswift2

How to embed a Youtube video into my app?


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!


Solution

  • 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) )
        }
    }