Swift library for embedding and controlling YouTube videos in your iOS applications via WKWebView!

Overview

YouTubePlayer

Embed and control YouTube videos in your iOS applications! Neato, right? Let's see how it works.

0.7.0 Update: WKWebView breaking changes

Installation

Carthage

Add this to your Cartfile:

github "gilesvangruisen/Swift-YouTube-Player"

…and then run carthage update

Don't forget to:

  • add YouTubePlayer.framework to the Link binary with libraries build phase
  • add YouTubePlayer.framework as an input file to the carthage copy-frameworks run script phase (only necesasry if you're building for iOS)

See Carthage for more information about using Carthage as a dependency manager.

Cocoapods

Ensure you are opting into using frameworks with use_frameworks!. Then add the following to your Podfile:

pod 'YouTubePlayer'

…and then run pod install.

Example

// Import Swift module
import YouTubePlayer

Build and lay out the view however you wish, whether in IB w/ an outlet or programmatically.

@IBOutlet var videoPlayer: YouTubePlayerView!
// init YouTubePlayerView w/ playerFrame rect (assume playerFrame declared)
var videoPlayer = YouTubePlayerView(frame: playerFrame)

Give the player a video to load, whether from ID or URL.

// Load video from YouTube ID
videoPlayer.loadVideoID("nfWlot6h_JM")
// Load video from YouTube URL
let myVideoURL = NSURL(string: "https://www.youtube.com/watch?v=wQg3bXrVLtg")
videoPlayer.loadVideoURL(myVideoURL!)

Controlling YouTubePlayerView

Each YouTubePlayerView has methods for controlling the player (play, pause, seek, change video, etc.) They are:

  • func loadVideoURL(videoURL: NSURL)
  • func loadVideoID(videoID: String)
  • func loadPlaylistID(playlistID: String)
  • func play()
  • func pause()
  • func stop()
  • func clear()
  • func seekTo(seconds: Float, seekAhead: Bool)
  • func previousVideo()
  • func nextVideo()
  • func getCurrentTime(completion: ((Double?) -> Void)?)
  • func getDuration(completion: ((Double?) -> Void)?))

Please note that calls to all but the first two methods will result in a JavaScript runtime error if they are called before the player is ready. The player will not be ready until shortly after a call to either loadVideoURL(videoURL: NSURL) or loadVideoID(videoID: String). You can check the readiness of the player at any time by checking its ready: Bool property. These functions run asynchronously, so it is not guaranteed that a call to a play function will be safe if it immediately follows a call to a load function. I plan to update the library soon to add completion handlers to be called when the player is ready.

In the meantime, you can also the YouTubePlayerDelegate method playerReady(videoPlayer: YouTubePlayerView) to ensure code is executed immediately when the player becomes ready.

Responding to events

YouTube's iFrame player emits certain events based on the lifecycle of the player. The YouTubePlayerDelegate outlines these methods that get called during a player's lifecycle. They are:

  • func playerReady(videoPlayer: YouTubePlayerView)
  • func playerStateChanged(videoPlayer: YouTubePlayerView, playerState: YouTubePlayerState)
  • func playerQualityChanged(videoPlayer: YouTubePlayerView, playbackQuality: YouTubePlaybackQuality)

Side note: All these delegate methods are optional which means that you can implement none, all, or some of them in your delegate class.

Breaking Changes

0.7.0 Transitioning from UIWebView (deprecated) to WKWebView required changing player calls which return values to be asynchronous. If you upgrade to 0.7.0, you will need to replace any call to either getCurrentTime() and getDuration() with its asynchronous equivalent, documented above.

Comments
  • Unexpectedly found nil while unwrapping an optional value if using cocoa pods

    Unexpectedly found nil while unwrapping an optional value if using cocoa pods

    In this function

    private func playerHTMLPath() -> String {
            return NSBundle(forClass: self.classForCoder).pathForResource("YTPlayer", ofType: "html")!
    }
    
    opened by AlexChesters 12
  • Cannot play VEVO videos

    Cannot play VEVO videos

    When I go to play a video that is under the VEVO umbrella I get a message:

    "This video contains content from VEVO. It is restricted from playback on certain sites. Watch on YouTube."

    opened by Jalsemgeest 9
  • No such module 'YouTubePlayer'

    No such module 'YouTubePlayer'

    Got

    screen shot 2016-04-04 at 1 12 22 pm

    /Users/qadirhussain/Downloads/Swift-YouTube-Player-master/YouTubePlayerExample/YouTubePlayerExample/ViewController.swift:10:8: No such module 'YouTubePlayer'

    opened by qadirsuh 8
  • Submitting to App Store

    Submitting to App Store

    Has anyone tried to submit an app to the App Store using this? It uses UIWebView, which has been deprecated in favor of WKWebView. The App Store Review Guidelines state:

    2.5.6 Apps that browse the web must use the appropriate WebKit framework and WebKit Javascript.

    opened by alexkitcoff 7
  • App crashing in iOS 12

    App crashing in iOS 12

    I have started using this library in iOS 12 and when I drag video player around the screen then my app is getting crashed. But it is working fine in iOS 11 and 10. Any fix for iOS 12?

    opened by Ganesh1924 7
  • Exceptions thrown

    Exceptions thrown

    Are you aware that the symbolic breakpoint "All Exceptions" catches a lot of exception when a video is played? Is this ok or can it be improved?

    bug 
    opened by ogezue 7
  • i am not able to play video automatically and also not able to remove suggestion

    i am not able to play video automatically and also not able to remove suggestion

    let myVideoURL = NSURL(string:urlString) videoPlayer.playerVars = [ "playsinline": "1", "controls": "1", "autoplay": "1", "showinfo": "1", "autohide":"1", "modestbranding":"1", "rel":1

        ]
    
        videoPlayer.loadVideoURL(myVideoURL!)
        self.youtubeView .addSubview(videoPlayer)
    

    here is my code. i want to remove red button and want to auto play the video.i also want to remove suggestion video and advertisement (if possible).please help me thank you.

    opened by ghimireprashant 7
  • Use WKWebView + fix various issues

    Use WKWebView + fix various issues

    Refactor to WKWebView and fix various issues:

    • fix #172
    • fix #171
    • fix #164

    @gilesvangruisen: I've only done minimal testing as my main focus was to fix the iOS 12 issue, so you might want to do some additional testing. If you merge this, could you please also make a new release and push it to cocoapods? Doing so should also resolve #169

    opened by weakfl 6
  • Easier way to ensure video plays inline on iPhone

    Easier way to ensure video plays inline on iPhone

    YTPlayer wants to play videos fullscreen on iPhone and inline on iPad. There is a setting to change this in the playerVars so that the video always plays inline, but it took some time and research to get it working for me.

    I propose a new property to make this easier for new users:

    /// by default, the youtube player will not play inline on iPhone
    /// setting this to true will force it to play inline
    var alwaysPlayInline : Bool {
        get {
            if let playsinline = playerVars["playsinline"] as? String {
                return playsinline == "1"
            }
            return false
        }
        set {
            playerVars["playsinline"] = "\(newValue ? 1 : 0)" as AnyObject?
          }
    }
    
    opened by jaywardell 6
  • UIWebView inherent memory leak showing up in YouTubePlayer

    UIWebView inherent memory leak showing up in YouTubePlayer

    The best option would be up somehow upgrade from UIWebView to WKWebView; however, until that happens, there needs to be a mechanisms for handling the memory link issue inherent to UIWebView. Since the webView variable is private, there is no way to access it to clear it manually.

    opened by stepwellmedia 6
  • Play next video in playlist?

    Play next video in playlist?

    I just started using this library and I have a playlist of videos I'd like to play.

    I have:

    func playerReady(videoPlayer: YouTubePlayerView)
        {
            print("ready")
            if videoPlayer.ready
            {
                videoPlayer.loadPlaylistID("PLxnnlv22Xcq14K9mn7qAg4uTQ4_D-ys9l")
            }
        }
    

    which I call and pass in playerReady(self.videoPlayer).

    However, I'm still a beginner. The beginning of the video just flashes constantly and doesn't play. I know I'm doing something wrong, but I'm not sure how to set it up.

    Can anyone assist?

    opened by seenoevo 6
  • Remove enum prefixes and lowercase the cases

    Remove enum prefixes and lowercase the cases

    In line with the latest Swift standards I'm proposing to lowercase enum cases. Also, I removed "YouTube" prefix from enum names as we can already infer that.

    opened by qalandarov 0
  • Live video plays for last 2:00:00 hours only.

    Live video plays for last 2:00:00 hours only.

    I have a video which was Live Streamed on Youtube. After the live stream got over and the complete video was available then the Video length was approximately 5:54:00.
Now when I try to play that video on the Youtube Player it shows only last 2 hours of that particular video.
How shall we play the complete video?

    opened by ankit0812 0
  • Need to add playback speed control

    Need to add playback speed control

    Hi, I tried to add speed control by adding the following functions in your YouTubePlayer. "func getPlaybackRate()" " "func getAvailablePlaybackRates(completion: )" "func setPlaybackRate(suggestedRate:Double)" The functions "getPlaybackRate" and "getAvailablePlaybackRates" worked fine but "setPlaybackRate" caused the error. Is there any way to control playback speed?

    The error observed by "setPlaybackRate" is as follows. Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=SyntaxError: Unexpected token ':', WKJavaScriptExceptionColumnNumber=0, WKJavaScriptExceptionSourceURL=about:blank, NSLocalizedDescription=A JavaScript exception occurred} ["[YouTubePlayer]", "Error executing javascript"] Thank you,

    opened by ymatt345 1
Releases(v0.7.2)
Owner
Giles Van Gruisen
Web, mobile, and IoT product development. Prev. @thoughtbot
Giles Van Gruisen
YoutubeKit is a video player that fully supports Youtube IFrame API and YoutubeDataAPI for easily create a Youtube app

YoutubeKit YoutubeKit is a video player that fully supports Youtube IFrame API and YoutubeDataAPI to easily create Youtube applications. Important Ref

Ryo Ishikawa 555 Dec 28, 2022
YouTubePlayerKit A Swift Package to easily play YouTube videos 📺

A Swift Package to easily play YouTube videos ??

Sven Tiigi 304 Jan 7, 2023
A lightweight app to play videos from the Files app in a better (dark) interface which avoids losing your playback position.

Playerly Playerly is a very lightweight Swift app that allows you to select a file (video or movie) from the built in Document Browser, and play it in

Julian Schiavo 28 Dec 3, 2022
Collection of Swift/iOS-related conference videos. A demo project for SuperArc framework - building modular iOS apps with a µComponent architecture.

SwiftCommunity Beta version is available at TestFlight Collection of Swift/iOS-related conference videos. This project serves as a showcase for the Su

SuperArcSwift 52 Dec 2, 2022
MMPlayerView - Custom AVPlayerLayer on view and transition player with good effect like youtube and facebook

MMPlayerView Demo-Swift List / Shrink / Transition / Landscape MMPlayerLayer ex. use when change player view frequently like tableView / collectionVie

Millman Yang 724 Nov 24, 2022
YouTube video player for iOS, tvOS and macOS

About XCDYouTubeKit is a YouTube video player for iOS, tvOS and macOS. Are you enjoying XCDYouTubeKit? You can say thank you with a tweet. I am also a

Cédric Luthi 2.9k Jan 7, 2023
The front-end of youtube iOS app developed using swift 5

Youtube-Front-end-iOS The front-end of youtube iOS app developed using swift 5 UIs 1)-The UI that corresponds to Home Tab bar "The first View " The fi

null 1 Nov 28, 2021
ABMediaView can display images, videos, as well as now GIFs and Audio!

Media view which subclasses UIImageView, and can display & load images, videos, GIFs, and audio and from the web, and has functionality to minimize from fullscreen, as well as show GIF previews for videos.

Andrew Boryk 80 Dec 20, 2022
This project is a clone of YouTube. But the main intention is to show how to write clean code, using proper MVC patterns and re-usable coding methodologies!

YouTubeClone This project is a clone of YouTube. But the main intention is to show how to write clean code, using proper MVC patterns and re-usable co

Vamshi Krishna 169 Dec 10, 2022
WatchTube: a standalone WatchOS youtube player utilizing Download API for search data and video streaming

WatchTube is a standalone WatchOS youtube player utilizing Download API for sear

WatchTubeTeam 11 May 30, 2022
Lightweight YouTube Downloader for iOS

DownTube DownTube is a very lightweight app that allows you to download any YouTube video for offline use. Note: this app goes against YouTube's TOS a

Adam Boyd 158 Dec 10, 2022
This Google Cast demo app shows how to cast videos from an iOS device in a way that is fully compliant with the Cast Design Checklist.

CastVideos-ios (reference iOS sender app) This Google Cast demo app shows how to cast videos from an iOS device in a way that is fully compliant with

Google Cast 168 Jan 6, 2023
Camera and Microphone streaming library via RTMP, HLS for iOS, macOS, tvOS.

HaishinKit (formerly lf) Camera and Microphone streaming library via RTMP, HLS for iOS, macOS, tvOS. Issuesの言語は、日本語が分かる方は日本語でお願いします! Sponsored with ??

shogo4405 2.4k Dec 29, 2022
YouTube player for SwiftUI

SwiftUI YouTube Player for iOS and MacOS Fully functional, SwiftUI-ready YouTube player for iOS 14+ and MacOS 11+. Actions and state are both delivere

Gordan Glavaš 12 Dec 25, 2022
reward the user for watching videos to get coins then use them to get rid of annoying admob ads

reward the users for watching youtube videos to the end to earn coins, then use them to get rid of annoying admob ads like banners, interstitial & reward videos

Belal Samy 4 Nov 19, 2021
📺 A news app using YouTube playlists, built with React Native

NewsWatch-React-Native A YouTube News app for iOS, made with React-Native. Enjoy watching your daily news. Screencast: This project was bootstrapped w

brad oyler 156 Jun 8, 2022
Catalyst example of a grid-based video app that opens videos in secondary windows

Simple Catalyst example (Mac idiom) of a grid-based app populated with videos. On macOS, double-clicking a video opens it in a new playback window. Keyboard navigation is fully supported via the UIKit Focus Engine.

Steven Troughton-Smith 19 Dec 8, 2022
MacTube is a webview wrapper for YouTube for Mac OS.

MacTube MacTube is a webview wrapper for YouTube for Mac OS. It was made for peo

null 33 Dec 26, 2022
A YouTube copy for the Victor Roldan Dev channel

YouTubeClone La idea de la creación de este proyecto, es que tu tengas la oportunidad de ver como es el desarrollo completo de una aplicación, desede

Victor Roldan 11 Dec 27, 2022