YoutubeKit is a video player that fully supports Youtube IFrame API and YoutubeDataAPI for easily create a Youtube app

Overview

YoutubeKit

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

Swift Cocoapods Carthage License

Important Referecens

YoutubeKit is created based on the following references. If you are unsure whether it is a normal behavior or a bug, please check the following documents first.

Example

This is an app using YoutubeKit. A simple video playback example is included into Example. You can create these functions very easily by using YoutubeKit.

Example1 Example2
Feed Comment
Example3 Example4
Floating Rotate

What is YoutubeKit?

YoutubeKit provides useful functions to create Youtube applications. It consists of the following two functions.

  • YTSwiftyPlayer (WKWebView + HTML5 + IFrame API)

  • YoutubeDataAPI

YTSwiftyPlayer

YTSwiftyPlayer is a video player that supports Youtube IFrame API.

Features:

  • High performance (Performance is 30% better than traditional UIWebView based player)
  • Low memory impact (maximum 70% off)
  • Type safe parameter interface(All IFrame API's parameters are supported as VideoEmbedParameter)

YoutubeDataAPI

This library supports YoutubeDataAPI (v3). For the details is Here.

Available API lists:

  • Actitivty(list)
  • Actitivty(insert)
  • Caption(list)
  • Channel(list)
  • ChannelSections(list)
  • Comment(list)
  • CommentThreads(list)
  • GuideCategories(list)
  • PlaylistItems(list)
  • Playlists(list)
  • Search(list)
  • Subscriptions(list)
  • VideoAbuseReportReasons(list)
  • VideoCategories(list)
  • Videos(list)

Get Started

Playback the youtube video.

import YoutubeKit

final class VideoPlayerController: UIViewController {

    private var player: YTSwiftyPlayer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Create a new player
        player = YTSwiftyPlayer(
                    frame: CGRect(x: 0, y: 0, width: 640, height: 480),
                    playerVars: [.videoID("videoID-abcde")])

        // Enable auto playback when video is loaded
        player.autoplay = true
        
        // Set player view.
        view = player

        // Set delegate for detect callback information from the player.
        player.delegate = self
        
        // Load the video.
        player.loadPlayer()
    }
}

YTSwiftyPlayerDelegate

YTSwiftyPlayerDelegate supports folowing delegate methods.

func playerReady(_ player: YTSwiftyPlayer)
func player(_ player: YTSwiftyPlayer, didUpdateCurrentTime currentTime: Double)
func player(_ player: YTSwiftyPlayer, didChangeState state: YTSwiftyPlayerState)
func player(_ player: YTSwiftyPlayer, didChangePlaybackRate playbackRate: Double)
func player(_ player: YTSwiftyPlayer, didReceiveError error: YTSwiftyPlayerError)
func player(_ player: YTSwiftyPlayer, didChangeQuality quality: YTSwiftyVideoQuality) 
func apiDidChange(_ player: YTSwiftyPlayer)    
func youtubeIframeAPIReady(_ player: YTSwiftyPlayer)    
func youtubeIframeAPIFailedToLoad(_ player: YTSwiftyPlayer)

Call IFrame API during playback.

// Pause the video.
player.pauseVideo()

// Seek after 15 seconds.
player.seek(to: 15, allowSeekAhead: true)

// Set a mute.
player.mute()

// Load another video.
player.loadVideo(videoID: "abcde")

Get video information using YoutubeDataAPI

First, Get API key from Here.

Next, add this code in your AppDelegate.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // Set your API key here
    YoutubeKit.shared.setAPIKey("Your API key")

    return true
}

And then you can use YoutubeDataAPI request like this.

// Get youtube chart ranking
let request = VideoListRequest(part: [.id, .statistics], filter: .chart)

// Send a request.
ApiSession.shared.send(request) { result in
    switch result {
    case .success(let response):
        print(response)
    case .failed(let error):
        print(error)
    }
}

Example of response here.

VideoList(items: [YoutubeKit.Video(etag: "\"A8kisgyDEbllhHF9ooXPFFrkc/nR6_A9oyIoLTJuucY_UXeasjYNU\"",
kind: "youtube#video",
id: "jeiDjeJgF0",
contentDetails: nil,
statistics: Optional(YoutubeKit.Statistics.VideoList(dislikeCount: "1631", likeCount: "60307", commentCount: Optional("8675"), favoriteCount: "0", viewCount: "1259046")),
snippet: nil,
status: nil),
etag: "\"J67fSnfblalhHF0foXPiFFrkc/TZGPJdE22-LilSv4-3VNoPw1cS4\"",
kind: "youtube#videoListResponse",
pageInfo: YoutubeKit.PageInfo(resultsPerPage: 5, totalResults: 200))

Fetch the next page (Pagination)

var nextPageToken: String?
...

// Send some request
ApiSession.shared.send(request) { [weak self] result in
    switch result {
    case .success(let response):
    
        // Save nextPageToken
        self?.nextPage = response.nextPageToken
    case .failed(let error):
        print(error)
    }
}
...

// Set nextPageToken
let request = VideoListRequest(part: [.id], filter: .chart, nextPageToken: nextPageToken)

Authorization Request

If you want authorized request such as a getting your activity in Youtube, you set your access token before sending a request. To use GoogleSignIn, you can easily get your access token. pod 'GoogleSignIn'

First, add this code in your AppDelegate.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // Set your access token for autheticate request
    YoutubeKit.shared.setAccessToken("Your access token")

    return true
}

And then you can use request requiring authorization, this is an example to get your Youtube activity.

// Get your Youtube activity
let request = ActivityListRequest(part: [.snippet], filter: .mine(true))

// Send a request.
ApiSession.shared.send(request) { result in
    switch result {
    case .success(let video):
        print(video)
    case .failed(let error):
        print(error)
    }
}

Requirements

XCode 10.2+

Swift 4+

Installation

Cocoapods

$ pod repo update

And add this to your Podfile:

pod 'YoutubeKit'

and

$ pod install

Carthage

Add this to your Cartfile:

github "rinov/YoutubeKit"

and

$ carthage update

Author

Github: https://github.com/rinov

Twitter: https://twitter.com/rinov0321

Email: rinov[at]rinov.jp

License

YoutubeKit is available under the MIT license.

Comments
  • Is there any way to stop showing

    Is there any way to stop showing "More Videos" in the player

    As described on the title. This library fits most of my product requirements which is amazing, except the "More Viedo" bar in the video player. Is there any where to solve it? Thank you!

    question 
    opened by talis00051 7
  • this video is not available

    this video is not available

    Thanks for the update player.

    If you bringup the following URL in your browser, it will play fine.

    https://youtu.be/BJq4d1-lHq8

    If I set the following in the Example app ViewController using the above videoID:

        player = YTSwiftyPlayer(
            frame: CGRect(x: 0, y: 0, width: 640, height: 480),
            playerVars: [.playsInline(true), .videoID("BJq4d1-lHq8"), .loopVideo(false), .showRelatedVideo(false)])
    

    I receive the error "this videos is not available".

    Though, using the swift player here:

    https://github.com/gilesvangruisen/Swift-YouTube-Player

    This video plays when passing in the full URL https://youtu.be/BJq4d1-lHq8. Is there a means to pass in a full URL for video playback using YoutubeKit?

    I would prefer your player, as it appears more memory efficient.

    Thanks.

    opened by appsird 6
  • Swift Packages

    Swift Packages

    Hope this finds you well. Good job with Youtubkit. I was wondering if you plan to make it work with Swift packages. I'd like to use this with my new project and trying not to use Cocoapods. Thanks!

    opened by amberreyn 5
  • SetVolume or setPlaybackQuali don't work

    SetVolume or setPlaybackQuali don't work

    Hey @rinov , First: Thanks for this nice Library!

    I tried setting the Quality and the Volume, but both function didn't work.

    player = YTSwiftyPlayer( frame: youTubeView.frame, playerVars: [.videoID(videoID), .autoplay(true), .registerStartTimeAt(Int(currentTime)) ,             
                    .showInfo(true), .showRelatedVideo(false)])  
     // Set player view      
     ...      
     // Set delegate for detect callback information from the player
     player.delegate = self     
     player.setPlaybackQuality(getQuality())    
     player.setVolume(50)
    
    
    opened by TMXJojo 4
  • Details are too small

    Details are too small

    Can you please help me to solve this issue? "Watch later", "Share" and uploader account info is too much small, also Play button of Youtube is also small.

    Attaching screenshot if iPhone X simulator iOS 12.1

    Simulator Screen Shot - iPhone X - 2019-06-03 at 19 32 44

    opened by mrugeshtank 3
  • ViewController with player, help request with layout

    ViewController with player, help request with layout

    Hi, is always me 😅. I have a question about this screen:

    rotate

    How did you made the layout with full screen on rotation? I try to add the player to my view, set the frame and it worked correctly. But on rotation differently from example the player not goes fullscreen. Did you use Autolayout?

    question 
    opened by eugeniobaglieri 3
  • Start and End Time cannot be used after initialization

    Start and End Time cannot be used after initialization

    Following is the declaration of my player:

      player = YTSwiftyPlayer(
                    frame: CGRect(x: 0, y: 0, width: 640, height: 480),
                    playerVars: [.videoID("SfJzNVECVe8"), VideoEmbedParameter.showRelatedVideo(false), VideoEmbedParameter.playsInline(true), VideoEmbedParameter.showModestbranding(true), VideoEmbedParameter.showControls(VideoControlAppearance.show), VideoEmbedParameter.progressBarColor(VideoProgressBarColor.white), VideoEmbedParameter.registerStartTimeAt(10), VideoEmbedParameter.registerEndTimeAt(35)])
    
            player.setPlayerParameters([VideoEmbedParameter.registerStartTimeAt(50), VideoEmbedParameter.registerEndTimeAt(55)])
    
            // Enable auto playback when video is loaded
    
            // Set player view.
            view.addSubview(player)
    
            // Set delegate for detect callback information from the player.
            player.delegate = self
    
    
            // Load the video.
            player.loadPlayer()
    

    I am getting "An error ocurred ....". If I remove the following line:

            player.setPlayerParameters([VideoEmbedParameter.registerStartTimeAt(50), VideoEmbedParameter.registerEndTimeAt(55)])
    
    

    it works as expected.

    Is this behaviour expected?

    opened by larjohn 3
  • auto play not working

    auto play not working

    Hi @rinov Thanks for answesome library. I just try with auto play when load video, but it's seem not work, the code is your example:

    player = YTSwiftyPlayer(
                frame: CGRect(x: 0, y: 0, width: 640, height: 480),
                playerVars: [.autoplay(true), .playsInline(true), .videoID("NPiYTw8WkyU")])
    
    

    Could you please detect why? Thanks a million!

    question 
    opened by hungnguyend 3
  • swift 4.1 init

    swift 4.1 init

    A compiler error after update to swift 4.1

    'self' used in method call 'defaultConfiguration' before 'super.init' call !!!

    public init(frame: CGRect = .zero, playerVars: [String: AnyObject]) {
        super.init(frame: frame, configuration: defaultConfiguration())
        
        commonInit()
        self.playerVars = playerVars
    }
    
    public init(frame: CGRect = .zero, playerVars: [VideoEmbedParameter] = []) {
        super.init(frame: frame, configuration: defaultConfiguration())
        
        commonInit()
        guard !playerVars.isEmpty else { return }
        var params: [String: AnyObject] = [:]
        playerVars.forEach {
            let property = $0.property
            params[property.key] = property.value
        }
        self.playerVars = params
    }
    
    opened by alfasolutions 3
  • [Full SPM Support]

    [Full SPM Support]

    Current implementation does not fully support SPM, especially loading resources. Version 0.5.0 shipped player.html internally, and it was available internally.

    Version 0.6.0 removed player.html, and now player.html should be added manually.

    This MR:

    1. bumps swift-tools to 5.3
    2. bumps minimum Xcode version to 12
    3. updates Package.swift so it will ship both sources and resources
    4. updates .podspec file to properly include sources and resources
    5. adds a method to load resource either from SPM or from Pod
    6. adds a method to load a default player.html
    7. updates Example project with SPM, and not Cocoapods
    enhancement 
    opened by maxkupetskii 2
  • Fix failing decode of Statistics

    Fix failing decode of Statistics

    Because Youtube API v3 doesn't return anymore the dislikeCount, the decode of the struct was failing, making the whole request response decode failing if statistics part was requested.

    opened by Tibimac 2
  • Help Needed - How to optimize performance for frequent loading

    Help Needed - How to optimize performance for frequent loading

    I am currently creating an app that scrolls Youtube Videos like Tiktok.

    I am using TableView for horizontal scrolling. My code looks something like below and it works as expected, just that it doesn't seem to be enough. Each cell would have its own Youtube Video (which loads successfully due to this great library), but there is "accumulating" impact to the memory.

    What I mean is that, the more scrolling the user does, the higher memory needed, and eventually it affects the performance/scrolling, etc.

    So I tried to write a piece of code to .clearVideo() everytime, the video is out of visible area of the phone. But for some reason, it doesn't work and I am not able to look into evaluatePlayerCommand function.

    Could you please let me know how I can completely "remove" initially loaded Youtube Video, so it will not impact the memory performance?

    let visibleRows = activeExerciseTableView.indexPathsForVisibleRows
            
                    if let visibleRows = visibleRows {
                        visibleRows.forEach { indexPath in
                            if let cell = activeExerciseTableView.cellForRow(at: indexPath) as? ActiveExerciseTableViewCell, activeExerciseTableView.bounds.contains(cell.frame) {
                            
                                for (index, setViewModel) in cellExercise.sets.enumerated() {
                                    
                                    if indexPath.row != index {
                                        setViewModel.shouldPlayVideo = false
                                        
                                        cell.ytVideoPlayer.clearVideo()
    
                                    }
                                    
                                    else if indexPath.row == index {
                                        setViewModel.shouldPlayVideo = true
                                        
                                        cell.ytVideoPlayer.playVideo()
                                        
                                    }
                                
                                }
    
    opened by MichaelJoo 0
  • As far as I know, the YouTubeKit with my API key in AppDelegate and SearchListRequest in the ViewController doesn't work?  I set up everything correctly on Google Cloud w.r.t. YouTubeAPI.  What should I do now?

    As far as I know, the YouTubeKit with my API key in AppDelegate and SearchListRequest in the ViewController doesn't work? I set up everything correctly on Google Cloud w.r.t. YouTubeAPI. What should I do now?

    Please let me know if you can help.

    The output in question below.

    2021-09-02 07:39:46.943671-0500 Video-Track[5611:158258] WF: === Starting WebFilter logging for process Video-Track
    2021-09-02 07:39:46.943797-0500 Video-Track[5611:158258] WF: _userSettingsForUser : (null)
    2021-09-02 07:39:46.943892-0500 Video-Track[5611:158258] WF: _WebFilterIsActive returning: NO
    2021-09-02 07:39:47.227231-0500 Video-Track[5611:158490] [] nw_protocol_get_quic_image_block_invoke dlopen libquic failed
    {
        error =     {
            code = 403;
            errors =         (
                            {
                    domain = global;
                    message = "Requests from this iOS client application <empty> are blocked.";
                    reason = forbidden;
                }
            );
            message = "Requests from this iOS client application <empty> are blocked.";
            status = "PERMISSION_DENIED";
        };
    }
    unacceptableStatusCode(403)
    youtubeIframeAPIReady(_:)
    playerReady(_:)
    player(_:didChangeState:)
    player(_:didChangeState:)
    player(_:didChangeQuality:)
    2021-09-02 07:39:48.518544-0500 Video-Track[5611:158258] [assertion] Error acquiring assertion: <Error Domain=RBSAssertionErrorDomain Code=3 "Required client entitlement is missing" UserInfo={RBSAssertionAttribute=<RBSDomainAttribute| domain:"com.apple.webkit" name:"MediaPlayback" sourceEnvironment:"(null)">, NSLocalizedFailureReason=Required client entitlement is missing}>
    2021-09-02 07:39:48.518653-0500 Video-Track[5611:158258] [ProcessSuspension] 0x103162360 - ProcessAssertion: Failed to acquire RBS MediaPlayback assertion 'WebKit Media Playback' for process with PID 5614, error: Error Domain=RBSAssertionErrorDomain Code=3 "Required client entitlement is missing" UserInfo={RBSAssertionAttribute=<RBSDomainAttribute| domain:"com.apple.webkit" name:"MediaPlayback" sourceEnvironment:"(null)">, NSLocalizedFailureReason=Required client entitlement is missing}
    2021-09-02 07:39:48.519157-0500 Video-Track[5611:158258] [assertion] Error acquiring assertion: <Error Domain=RBSAssertionErrorDomain Code=3 "Required client entitlement is missing" UserInfo={RBSAssertionAttribute=<RBSDomainAttribute| domain:"com.apple.webkit" name:"MediaPlayback" sourceEnvironment:"(null)">, NSLocalizedFailureReason=Required client entitlement is missing}>
    2021-09-02 07:39:48.519227-0500 Video-Track[5611:158258] [ProcessSuspension] 0x103162390 - ProcessAssertion: Failed to acquire RBS MediaPlayback assertion 'WebKit Media Playback' for process with PID 5611, error: Error Domain=RBSAssertionErrorDomain Code=3 "Required client entitlement is missing" UserInfo={RBSAssertionAttribute=<RBSDomainAttribute| domain:"com.apple.webkit" name:"MediaPlayback" sourceEnvironment:"(null)">, NSLocalizedFailureReason=Required client entitlement is missing}
    player(_:didChangeState:)
    player(_:didUpdateCurrentTime:)
    player(_:didUpdateCurrentTime:)
    player(_:didUpdateCurrentTime:)
    player(_:didUpdateCurrentTime:)
    player(_:didUpdateCurrentTime:)
    player(_:didUpdateCurrentTime:)
    player(_:didUpdateCurrentTime:)
    
    
    opened by shyamalschandra 2
  • How to create custom view on video player

    How to create custom view on video player

    I am making video player in swift. I add some custom buttons and functionality for standard video player: 1. Playing video from URL (server) 2. Showing indicator while loading video like in VK 3. Add custom buttons to control (stop, pause buttons) and its working fine. I'm trying to implement custom view on player like below screen shot and play in custom duration in loop.

    I need this type of view on video player

    Screen Shot 1

    I can't understand how I can implement my tasks(For video url) there. Can you give some advice, which is the better way to do this?

    opened by shamdass 0
  • How detect event on close button over video player?

    How detect event on close button over video player?

    I want to know if is possible detect when the user tap over close button to close video player.

    Actually, the state return is "paused", but I need difference between paused button and close button. To shot an action over parent ViewController.

    Someone knows something about that?.

    Thanks friends.

    opened by ErwinJonn 0
  • Live Stream Embed

    Live Stream Embed

    First off, the library is great thank you so much! I just wanted to see if you could add support for a Youtube Live Stream. From what I see already done, it would be really easy to add. This is the link to get the iFrame embed for the Live Stream player -> "https://www.youtube.com/embed/live_stream?channel=(CHANNEL-ID)&autoplay=true&playsinline=1&enablejsapi=1" it would be really awesome if you could add that as an option and just be able to pass in the channelID for this type.

    opened by knawwxbackme 0
Releases(0.7.0)
Owner
Ryo Ishikawa
Ryo Ishikawa
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
A fully functional short video app project.Record a six secends video while playing prank sounds.

prankPro A fully functional short video app project How to Install 1. use coconapod to init your xcode environment. 2. change the app-keys in `applica

huijimuhe 258 Jun 19, 2022
JDVideoKit - You can easily transfer your video into Three common video type.

JDVideoKit Introduction You can easily transfer your video into Three common video type. You can use set up camera easily. Installation pod 'JDVideoK

郭介騵 24 Sep 9, 2021
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 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
Musical Player - A Simple Musical Player For iOS

Musical_Player The app is a musical player. It was written as an task for a mobi

null 1 Nov 26, 2022
A Swift library to upload video files to api.video platform.

api.video IOS video uploader api.video is the video infrastructure for product builders. Lightning fast video APIs for integrating, scaling, and manag

api.video 7 Dec 9, 2022
api.video is the video infrastructure for product builders

api.video is the video infrastructure for product builders. Lightning fast video APIs for integrating, scaling, and managing on-demand & low latency live streaming features in your app.

api.video 4 Jun 27, 2022
Loop videos on iOS and Android (assuming only one video like on YouTube)

Mobile Video Loop By: Andrew-Chen-Wang iOS Safari Extension (soon Android) that lets you loop a video on your current website. This only works for the

Andrew Chen Wang 0 Dec 19, 2021
Yattee: video player for Invidious and Piped built for iOS 15, tvOS 15 and macOS Monterey

Video player with support for Invidious and Piped instances built for iOS 15, tvOS 15 and macOS Monterey.

Yattee 1k Dec 27, 2022
Yattee: video player for Invidious and Piped built for iOS, tvOS and macOS

Video player for Invidious and Piped instances built for iOS, tvOS and macOS. Features Native user interface built with SwiftUI Multiple instances and

Yattee 1.1k Jan 8, 2023
Hide the "Latest Video Performance" tab in YouTube Studio

Hide Latest Video Performance - YT Studio Extension that hides the stupid YouTube Studio "Latest Video Performance" / "Latest YouTube Short Performanc

Taranasus 2 Jul 22, 2022
▶️ video player in Swift, simple way to play and stream media on iOS/tvOS

Player Player is a simple iOS video player library written in Swift. Looking for an obj-c video player? Check out PBJVideoPlayer (obj-c). Looking for

patrick piemonte 2k Jan 2, 2023
📽 A video player for SwiftUI, support for caching, preload and custom control view.

Features QuickStart Advances Installation Requirements License Demo Clone or download the project. In the terminal, run swift package resolve. Open Vi

Gesen 437 Jan 5, 2023
iOS video player for trailer. You can customize layout for the control panel. Support PiP and DRM.

iOS video player for trailer. You can customize layout for the control panel. Support PiP and DRM.

Abe Wang 11 Nov 7, 2022
Versatile Video Player implementation for iOS, macOS, and tvOS

News ?? - Since 2.1.3 VersaPlayer now supports iOS, macOS, and tvOS Example Installation Usage Basic Usage Adding Controls Advanced Usage Encrypted Co

Jose Quintero 723 Dec 26, 2022
BMPlayer - A video player for iOS, based on AVPlayer, support the horizontal, vertical screen

A video player for iOS, based on AVPlayer, support the horizontal, vertical screen. support adjust volume, brightness and seek by slide, support subtitles.

Eliyar Eziz 1.8k Jan 4, 2023
Overlay alpha channel video animation player view using Metal.

Overlay alpha channel video animation player view using Metal. Example To run the example project, clone the repo, and run pod install from the Exampl

noppefoxwolf 244 Jan 1, 2023
Swifty360Player - iOS 360-degree video player streaming from an AVPlayer.

Swifty360Player iOS 360-degree video player streaming from an AVPlayer. Demo Requirements Swifty360Player Version Minimum iOS Target Swift Version 0.2

Abdullah Selek 148 Dec 18, 2022