How can I avoid fullscreen when playing a video in Swift 2.0?
let Code:NSString = "<iframe width=255 height=135 src=http://www.youtube.com/embed/eVk3TMB1JWY?autoplay=1&fs=0 frameborder=0 allowfullscreen=false></>"
I both tried fs=0 and allowfullscreen=false but neither work.
When the video shows up in my webview, the info about the video is also shown; how can I avoid this too?
From what you're describing, it sounds like you want to play the video "inline." Pass in whatever width and height values you want into the UIWebView constructor to allow inLine playback without the video popping open to its full screen player.
let webView = UIWebView(frame: self.view.frame) // or your custom CGRect
self.view.addSubview(webView)
self.view.bringSubviewToFront(webView)
webView.allowsInlineMediaPlayback = true
webView.mediaPlaybackRequiresUserAction = false
let videoID = "zN-GGeNPQEg" // https://www.youtube.com/watch?v=zN-GGeNPQEg
let embededHTML = "<html><body style='margin:0px;padding:0px;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>function onYouTubeIframeAPIReady(){ytplayer=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}function onPlayerReady(a){a.target.playVideo();}</script><iframe id='playerId' type='text/html' width='\(self.view.frame.size.width)' height='\(self.view.frame.size.height)' src='http://www.youtube.com/embed/\(videoID)?enablejsapi=1&rel=0&playsinline=1&autoplay=1' frameborder='0'></body></html>"
webView.loadHTMLString(embededHTML, baseURL: NSBundle.mainBundle().resourceURL)
You just need to delete allowfullscreen from the link. Your link will look like this:
http://www.youtube.com/embed/eVk3TMB1JWY?autoplay=1&fs=0 frameborder=0 >
Related
The problem:
I am trying to resize the text / content that is being displayed in a WKWebView. The content itself is loaded from a remote source (via loadHTMLString), so I cannot change the css.
I already tried most other solutions I could find on stack overflow (like https://stackoverflow.com/a/43694902/1673377), but none seem to work.
Some background:
Xcode 9.2, Swift 4, iOS 10 / 11.
To monitor the content size, I used the code taken from here: https://stackoverflow.com/a/41511422/1673377
lazy var webView: WKWebView = {
//Javascript string
let source = "window.onload=function () {window.webkit.messageHandlers.sizeNotification.postMessage({justLoaded:true,height: document.body.scrollHeight});};"
let source2 = "document.body.addEventListener( 'resize', incrementCounter); function incrementCounter() {window.webkit.messageHandlers.sizeNotification.postMessage({height: document.body.scrollHeight});};"
//UserScript object
let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
let script2 = WKUserScript(source: source2, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
//Content Controller object
let controller = WKUserContentController()
//Add script to controller
controller.addUserScript(script)
controller.addUserScript(script2)
//Add message handler reference
controller.add(self, name: "sizeNotification")
//Create configuration
let configuration = WKWebViewConfiguration()
configuration.userContentController = controller
return WKWebView(frame: CGRect.zero, configuration: configuration)
}()
To disable zooming, I also evaluate the following JavaScript:
"var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);"
(I tried playing around with the values for initial-scale and maximum-scale, but to no avail.)
Any help would be greatly appreciated!
Basic Goal
If you want to change the font size, you somehow need CSS. Your goal therefore should be to inject the following 2 lines somewhere in the html header:
<link rel='stylesheet' href='style.css' type='text/css'>
<meta name='viewport' content='initial-scale=1.0'/> // This may help with scale
If you add a style.css file to your project, it now should be respected.
Actual implementation
I don't know how the html you receive from the server is configured, but you could try to manipulate it a bit like this before loading it onto the WKWebView:
let customHeader = <link rel='stylesheet' href='style.css' type='text/css'><meta name='viewport' content='initial-scale=1.0'/>
let newHtml = serverHtml.replacingOccurrences(of: "<head>", with: "<head>" + customHeader)
I'm loading Youtube video inside UIWebView using following code.
let videoUrl = "https://www.youtube.com/embed/F9GujgK0y2M"
let embedHTML = "<iframe width=\(self.webView.frame.size.width)\" height=\(self.webView.frame.size.height)\" src=\(videoUrl)?&playsinline=1\" frameborder=\"0\" allowfullscreen></iframe>"
Starting thumbnail for video is very large. I need to fit it according to size of UIWebView. Please help me, How can I change it ?
maybe this code can help you:
let yourVideoID = "F9GujgK0y2M"
let css = ".video-container {position:relative;padding-bottom:56.25%;height:0;overflow:hidden;} .video-container iframe, .video-container object, .video-container embed { position:absolute; top:0; left:0; width:100%; height:100%; }"
let url = "https://www.youtube.com/embed/\(yourVideoID)?playsinline=1&modestbranding=1&showinfo=0&rel=0&showsearch=0&loop=1&iv_load_policy=3"
let htmlString = "<html><head><style type=\"text/css\">\(css)</style></head><body><div class=\"video-container\"><iframe src=\"\(url)\" frameborder=\"0\"></iframe></div></body></html>"
yourWebView.scalesPageToFit = false
yourWebView.allowsInlineMediaPlayback = true;
yourWebView.loadHTMLString(htmlString, baseURL: nil)
Try this:
webView.scalesPageToFit = true
From Apple Documentation, setting this to true scales the webpage to fit the screen.
For me, removing the height and width properties in the iframe HTML tag made the frame fit the page width altogether.
I have embedded HTML5 video with mp4 format. How to get thumbnail image like poster without using "poster" attribute. This problem coming on Safari and iOS. I have added video like below mentioned code.
<video height=350 id='TestVideo' webkit-playsinline><source src='test.mp4' type=video/mp4></video>
On Chrome, IE, Firefox first frame of video coming as thumbnail image, but not coming on Safari and iOS.
simply add preload="metadata" in video tag and set #t=0.1 at url src, it will get the frame of 0.1s of your video as thumbnail
however, the disadvantage of this solution is when you click to play the video, it always start at 0.1s
<video preload="metadata" controls>
<source src="video.mp4#t=0.1" type="video/mp4">
</video>
If you want to do this without storing server side images it is possible, though a bit clunky... uses a canvas to record the first frame of the video and then overlay that over the video element. It may be possible to use the URL for the Canvas as a source for the Poster (eg video.poster = c.toDataURL();) but that requires correct CORS setup (not sure if the video was on your own server, and if you have control over that, so took the safest option). This will work best if video is correctly encoded for streaming (so MOOV atom is at the front of the video, otherwise it will be slow to draw the overlay - see this answer for more detail)
The HEAD contains styling for the video and the overlay (you will need to adjust sizing and position to suit your application)
<head>
<style>
video_box{
float:left;
}
#video_overlays {
position:absolute;
float:left;
width:640px;
min-height:264px;
background-color: #000000;
z-index:300000;
}
</style>
</head>
In the BODY you will need the div for the overlay and the video. The overlay div has an onclick handler to hide the overlay and start the video playing
<div id="video_box">
<div id="video_overlays" onclick="this.style.display='none';document.getElementById('video').play()"></div>
<video id="video" controls width="640" height="264">
<source src="BigBuck.mp4" type='video/mp4'>
</video>
</div>
</div>
Finally you will need code that will load the video, seek to the first frame and load the visual into a canvas that you then insert into the overlay
<script>
function generateOverlay() {
video.removeEventListener('seeked',generateOverlay); / tidy up the event handler so it doesn't redraw the overlay every time the user manually seeks the video
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
c.width = 640;
c.height = 264;
ctx.drawImage(video, 0, 0, 640, 264); // take the content of the video frame and place in canvas
overlay.appendChild(c); // insert canvas into the overlay div
}
// identify the video and the overlay
var video = document.getElementById("video");
var overlay = document.getElementById("video_overlays");
// add a handler that when the metadata for the video is loaded it then seeks to the first frame
video.addEventListener('loadeddata', function() {
this.currentTime = 0;
}, false);
// add a handler that when correctly seeked, it generated the overlay
video.addEventListener('seeked', function() {
// now video has seeked and current frames will show
// at the time as we expect
generateOverlay();
}, false);
// load the video, which will trigger the event handlers in turn
video.load();
</script>
this is a bit late but we had the same scenario. I can't use the attribute 'muted' because my videos are podcasts. This is what I came up with and I hope to share it with future visitors. What I did is load the video in the body tag, drew a canvas, retrieved as base64 and applied to the video as the background image.
Since my video should be fixed 150px in height, I computed the aspect ratio so that whatever height and width of the actual video, it will be resized into 150px height and dynamic width.
$('body').append('<video class="checkmeload" style="position:absolute;top:-10000px" controls preload="auto" playsinline src="//src-here"><source src="//src-here" type="//videotype-here"></video>');
$('body').find('.checkmeload').on('loadeddata', function(){
var video = $('.checkmeload');
var canvas = document.createElement('canvas');
aspectratio = (video[0].videoWidth / video[0].videoHeight);
newwidth = (150 * aspectratio);
canvas.width = newwidth;
canvas.height = 150;
var context = canvas.getContext('2d');
context.drawImage(video[0], 0, 0, canvas.width, canvas.height);
var dataURI = canvas.toDataURL('image/jpeg');
$('body').find('.checkmeload').remove();
$('#myvideo').css('background-image','url("'+dataURI +'")');
});
Source: How to set the thumbnail image on HTML5 video?
This worked for me:
<img src="thumbnail.png" alt="thumbnail" />
/* code for the video goes here */
Now using jQuery play the video and hide the image as
$("img").on("click", function() {
$(this).hide();
// play the video now..
})
Add #t=0.001 at the end of the video URL.
https://muffinman.io/blog/hack-for-ios-safari-to-display-html-video-thumbnail/
I am trying to embed a video from youtube with the following code:
func setUpVideo() {
let width = webView.frame.width
let height = webView.frame.height
let frame = 0
bmiWebView.allowsInlineMediaPlayback = true
let videoUrl = "https://www.youtube.com/embed/GCALWdwKr48"
let htmlUrl = "<html><body><iframe width=\(width) height=\(height) src=\(videoUrl)?&playsinline = 1 frameborder=\(frame) allowfullscreen></iframe></body></html>"
webView.loadHTMLString(htmlUrl, baseURL: NSBundle.mainBundle().bundleURL)
}
I'm able to load the video initially with white background but when it loads it looks like below. I'm not sure why there is a white background. If someone can tell me how to remove that will be really helpful. Thank you.
The white background is the margin on the body of the HTML of your UIWebView.
Add some CSS to set the margin to 0 like so:
<html>
<head>
<style>body{margin:0px;}</style>
</head>
<body>
<iframe width=\(width) height=\(height) src=\(videoUrl)?&playsinline = 1 frameborder=\(frame) allowfullscreen></iframe>
</body>
</html>
<iframe width="100%" height="100%" src="//www.youtube.com/embed/qUJYqhKZrwA?autoplay=1&showinfo=0&controls=0" frameborder="0" allowfullscreen>
If you remove ?autoplay=1 the video does not work. Looks like you cannot use the controls parameter without autoplay enabled.
Not sure why this is not mentioned in the YouTube embed writeup.
Hope I'm wrong.
https://developers.google.com/youtube/player_parameters#controls
Set autoplay=0
<iframe width="100%" height="100%" src="//www.youtube.com/embed/qUJYqhKZrwA?autoplay=0&showinfo=0&controls=0" frameborder="0" allowfullscreen>
As seen here: Autoplay=0 Test
To continue using the iframe YouTube, you should only have to change ?autoplay=1 to ?autoplay=0.
Another way to accomplish this would be by using the YouTube JavaScript Player API. (https://developers.google.com/youtube/js_api_reference)
Edit: the YouTube JavaScript Player API is no longer supported.
<div id="howToVideo"></div>
<script type="application/javascript">
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = false;
ga.src = 'http://www.youtube.com/player_api';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
var done = false;
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('howToVideo', {
height: '390',
width: '640',
videoId: 'qUJYqhKZrwA',
playerVars: {
controls: 0,
disablekb: 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
console.log('onPlayerReady', evt);
}
function onPlayerStateChange(evt) {
console.log('onPlayerStateChange', evt);
if (evt.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
console.log('stopVideo');
player.stopVideo();
}
</script>
Here is a jsfiddle for the example: http://jsfiddle.net/fgkrj/
Note that player controls are disabled in the "playerVars" part of the player. The one sacrifice you make is that users are still able to pause the video by clicking on it. I would suggest writing a simple javascript function that subscribes to a stop event and calls player.playVideo().
use autoplay=0
autoplay takes 2 values.
Values: 0 or 1. Default is 0. Sets whether or not the initial video will autoplay when the player loads.
the important part
autoplay=0&showinfo=0&controls=0
Here is the demo for ur problem FIDDLE
?modestbranding=1&autohide=1&showinfo=0&controls=0
autohide=1
is something that I never found... but it was the key :) I hope it's help
If you add this ?showinfo=0&iv_load_policy=3&controls=0 before the end of your src, it will take out everything but the bottom right YouTube logo
working example: http://jsfiddle.net/42gxdf0f/1/
Follow this https://developers.google.com/youtube/player_parameters for more info about video controls like:
<iframe id="video_iframe" width="660" height="415" src="http://www.youtube.com/v/{{course_url}}?start=7&autoplay=0&showinfo=0&iv_load_policy=3&rel=0"
frameborder="0"
allowfullscreen></iframe>
start=7&autoplay=0&showinfo=0&iv_load_policy=3&rel=0"
frameborder="0"
all controls are described in there
To remove you tube controls and title you can do something like this
<iframe width="560" height="315" src="https://www.youtube.com/embed/zP0Wnb9RI9Q?autoplay=1&showinfo=0&controls=0" frameborder="0" allowfullscreen ></iframe>
code with output
showinfo=0 is used to remove title and &controls=0 is used for remove controls like volume,play,pause,expend.
You can hide the "Watch Later" Button by using "Youtube-nocookie" (this will not hide the share Button)
Adding controls=0 will also remove the video control bar at the bottom of the screen and using modestbranding=1 will remove the youtube logo at bottom right of the screen
However using them both doesn't works as expected (it only hides the video control bar)
<iframe width="100%" height="100%" src="https://www.youtube-nocookie.com/embed/fNb-DTEb43M?controls=0" frameborder="0" allowfullscreen></iframe>
Autoplay works only with /v/ instead of /embed/, so change the src to:
src="//www.youtube.com/v/qUJYqhKZrwA?autoplay=1&showinfo=0&controls=0"