Code Monkey home page Code Monkey logo

swift-youtube-player's Introduction

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.

swift-youtube-player's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swift-youtube-player's Issues

load another video after current one finish

Hi, I would like to load another video when playback of the current video is finish, how would I do that?
(I have an array of videoID and I would like to put them in a queue) is that possible?

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'

Restricted playback from VEVO

it seems like the base URL is not linked to http://www.youtube.com so when I try to view copyrighted content, it gives me this error message, I successfully play copyrighted video on a simple uiWebView and an iFrame,

let iframeString = "<iframe width="360" height="190" src="http://www.youtube.com/embed/RgKAFK5djSk?playsinline=1&autoplay=1&showinfo=0&modestbranding=1&autohide=1\" frameborder="0"></iframe>"

player.loadHTMLString(iframeString, baseURL: NSURL(string:"http://www.youtube.com"));

setting the baseURL parameter allow me to play any kind of video. is there a quick fix for that in your implementation?

getting warning

no rule to process file '/Users/archanavetkar/Documents/Marriager/Pods/YouTubePlayer/YouTubePlayer/YouTubePlayer/YTPlayer.html' of type text.html for architecture armv7
and for arm64

Carthage No Shared Scheme

I received the following message when attempting to install via Carthage:

Project "YouTubePlayer.xcodeproj" has no shared schemes

Is this the expected behavior? Thanks.

Full screen state

Hi

Is it possible to detect somehow if the video goes to full screen?

swift 3.0

Could you please make a branch that is swift 3.0 compatible?

Player volume controls

you said that i will make volume up down function later but i am waiting you for 2 mount :( please show me a way. How can i do that?

Adding the framework to project, can't Archive project for submit

Hi, nice work

In my project I add the library and is working ok on my device, even when I prepare de Archive for submision al works ok, but when I submit the file an error appear saying that is required the arm64 support.

If I add support for this architecture, I cant no longer build my project and get error like this:

class DRSEjercicio2Controller: UIViewController, WKScriptMessageHandler, YouTubePlayerDelegate{ On this line: Use of undeclared type YouTubePlayerDelegate

I have import YouTubePlayer and that line doesn't cause error

Can you give any advice? Is this library arm64 supported?

Thanks

load playlist from a specific song on a playlist

I am thinking on having a playlist of videos which will be shown on a collection view. Is there a way to play/load a playlist starting from a specific video?
I have seen that there is a single playlist ID for all of the songs in a playlist, and each video has a individual ID. But can I somehow combine these ID's to start a playlist from specific video

Best,
Ilir

Enable Airplay?

Hi! Has anyone been able to enable Airplay playback? I have added the "webView.mediaPlaybackAllowsAirPlay = true" to the swift file manually but that does not work. Any ideas?

Thanks!

Player still showing controls even after adding playerVars

Hi,

I'm working on a project and using your Swift Youtube player. Currently, when I set the playerVars to these values:

public static let YOUTUBE_PARAMS = [
"playsinline": "0",
"controls": "0",
"showinfo": "0",
"autoplay" : "1",
"fs" : "1",
"modestbranding" : "1"
]

The changes are not active when the video plays. I checked in the debugger and they are applied to the playerVars, but not in the control.

I have also tried hard coding the values into the .html files, only substituting the videoId. Controls are still visible, and user is able to user them. Parameters seem to have no effect. What could I be doing wrong?

EDIT: I have noticed this is not happening on IPad, but only on smaller devices.

IOS 9.2

Autoplay

I would like to be able to autoplay the video once it has loaded

Retain cycle

Currently public var delegate: YouTubePlayerDelegate? is strong reference, that causes to retain cycle.
Easy to fix, but I was unable to make a pull request, so:

  1. add word "class" to: public protocol YouTubePlayerDelegate : class { ... }
  2. public weak var delegate: YouTubePlayerDelegate?

unable to play with Carthage

Hello,
I am trying to build with Carthage but it doesn't work..
Facing some exception

Unknown class YouTubePlayerView in Interface Builder file.

YouTubePlayerView file is missing with

$(SRCROOT)/Carthage/Build/iOS/YouTubePlayer.framework

getDuration feature doesn't work

As the title suggests the getDuration feature didn't work in the example project or the project I'm working on now. Has anyone had this problem?

Add completion block support on `loadVideo…()` functions

Because of the delegate issue (lack of optional functions in Swift protocols, lack of compatibility between obj-c protocols and Swift enums, etc.), I'd like to make many of those common tasks easier and ultimately eliminate the need for a delegate at all.

Part of this includes adding support for completion blocks on loadVideo…() functions, to be called when the play becomes ready.

Cocoa Pods/Cathrage Don't Install

[XCODE 7.1 Swift 2]

Hey

I followed the instructions for adding the Carthage file and the I wasn't able to find the frameworks I had to add to the Link Library With Binary.

I tried adding the cocoa-pods and it just keeps "updating": "Updating local specs repositories" and doesn't change. I've been waiting for several minutes...

My project was set on iOS 9.1. I then set it to 7.0 and nothing changed.

Any ideas if I'm doing something wrong or if this is a bug for Swift 2?

Thanks guys.

Include the library in project

In the issue #2 there is a similar question but this issue is closed and I am not being able to include the library on my project or on the example project.
So as the example project is saved on Downloads folder my root directory I assume is User/Downloads/Swift-YouTube-Player-master/YouTubePlayerExample than in the root directory I am adding git init than git submodule add [email protected]:gilesvangruisen/Swift-YouTube-Player.git and in the end I am dragging YouTubePlayer.xcodeproj on the project directory.

Image 1

Image 1

But after I am adding the YouTubePlayer.framework on Embedded Binaries the library on Embedded Binaries is showing red and I am having an error saying: No such module "YouTubePlayer"

Thank you in advance

No such module "YouTubePlayer"

Hi, thanks for providing the swift realization of Youtube player view.
But when I tried to used your library, when I try to call:
import YouTubePlayer
in my ViewController file, the following error is reported:
No such module "YouTubePlayer"
Can you give me some hint?

Thanks very much!

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?

Current playback time/duration?

Thanks for making this, only issue I'm currently having is how to get the current playback time/total duration of the video?

Cannot change the video quality

Hi there,

I am not able to set the video quality. It is streaming the lowest quality at all times.

I set the default quality as follows:
private(set) public var playbackQuality = YouTubePlaybackQuality.HD720

Still cannot get the quality to be 720p. Any help would be appreciated.

Thank you.

Turn on fullscreen iPad?

Can't seem to be able to play full screen for iPad.

public func loadVideoID(videoID: String) {
var playerParams = playerParameters()
playerParams["videoId"] = videoID
playerParams["playsinline"] = "0"

    loadWebViewWithParameters(playerParams)
}

The video still plays in line. Any help?

Display lots of errors...even with your example project too..

when i installed this project library..it displays lots of errors ...then i check your project example and same problem occurs here too....
snip20150526_1

so...how to solve this..and please make some installation guide for user for your repository
Note : i installed this library manually

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."

Audio streaming

Just curious is there a way to download only audio from yt?

YouTubePlayerDelegate methods are not being called

Might be a newbie issue. But my delegates are not being called. My play and pause button do work, so that's fine. My code, (the three methods at the bottom are not being called)

import UIKit
import YouTubePlayer

class ViewController: UIViewController, YouTubePlayerDelegate {

    @IBOutlet var playerView: YouTubePlayerView!
    @IBOutlet var playButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        // setup the player
        playerView.playerVars = ["playsinline": "1"]
        playerView.loadVideoID("wQg3bXrVLtg")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func play(sender: UIButton) {
        println("play")

        if playerView.ready {

            if playerView.playerState != YouTubePlayerState.Playing {
                playerView.play()
                playButton.setTitle("Pause", forState: .Normal)
            } else {
                playerView.pause()
                playButton.setTitle("Play", forState: .Normal)
            }
        }
    }

    // these are not called:
    func playerStateChanged(videoPlayer: YouTubePlayerView, playerState: YouTubePlayerState) {
        println("playerStateChanged")
    }

    func playerReady(videoPlayer: YouTubePlayerView) {
        println("playerReady")
    }

    func playerQualityChanged(videoPlayer: YouTubePlayerView, playbackQuality: YouTubePlaybackQuality) {
       println("playerQualityChanged")
    }

}

Can't play videos on SplitViewController on iPad

Hello,

I'm using your library in one of my project (thanks in advice), it works perfectly on iPhone, but i doesn't work properly on iPad.

I use a collectionview on detailviewcontroller, every cell contains a YouTubePlayer view, and when user click an iten, collectionview's didselect methot trigger the player, and it plays on full screen, but on iPad, when i click the collectionView item, i think it plays on background, i can hear the video's voice, but cant see the video. What should i do to open player on splitviewcontroller with full screen?

Here is my collectionView's didSelect method:

    timer = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: "alertVideo", userInfo: nil, repeats: false)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "doneButton",  name: UIWindowDidBecomeHiddenNotification, object:nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "startVideo",  name: UIWindowDidBecomeVisibleNotification , object:nil)
    let a = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
    a.dimBackground = true
    collectionView.deselectItemAtIndexPath(indexPath, animated: true)
    let cell = collectionView.cellForItemAtIndexPath(indexPath)
    let circleView : YouTubePlayerView? = (cell!.contentView.viewWithTag(10)) as? YouTubePlayerView

    circleView?.play()

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?

Toggle fullscreen with no controls & pod outdated

How can I toggle fullscreen on a player with no controls? I've tried setting the autoscreen variable but size remains the same.

  videoPlayer.playerVars = [
            "playsinline": "1",
            "controls": "0"
        ]
   @IBAction func toggleFullScreen(sender: UIButton) {
        print("full screen")
        videoPlayer.playerVars = ["autoplay" : "1"]
        videoPlayer.reloadInputViews()
    }

PS the current pod doesnt include getCurrentTime() and getDuration()

Close webview after video finishes?

Is there a way to close the player webView after the video has ended? At the moment it remains full-screen and I have to manually press the player "Done" button to close it. (I'm working on an application for kids where I need the video player to automatically close after the video stops.) Any suggestions would be appreciated!

XCode 7, Pod Import

PodFile
1 platform :ios, '8.0'
2 use_frameworks!
3 pod 'YouTubePlayer'

Run pod install, pod update.

I create a new XCode project and import YoutubePlayer, but it says the module is not found. What is the cause for this? I'm running XCode 7.

No Such Module YouTubePlayer

I used CocoaPods to use your project however when I try to use it using

import YouTubePlayer

I get the error saying No Such Modue YouTubePlayer. I am on XCode 6.4

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.