I want to set thumbnail image in the uiwebview frame on my view. However when I use the following code, there is no image displayed, although the image value is NOT NULL. Can someone help and and let me knwo where am I going wrong?
Please note that in the code, the VideoView class is derived from UIWebView and works just like it.
video = [[VideoView alloc]
initWithStringAsURL:@"http://www.youtube.com/watch?v=T6X3j7zxUHA"
frame:CGRectMake(11, 7, 298, 311)];
[self addSubview:video];
UIGraphicsBeginImageContext(video.bounds.size);
[video.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultImageView = UIGraphicsGetImageFromCurrentImageContext();
thumbnailButton = [UIButton buttonWithType:UIButtonTypeCustom];
[thumbnailButton setFrame:CGRectMake(0,0, 298, 311)];
[thumbnailButton setImage:resultImageView forState:UIControlStateNormal];
[video addSubview:thumbnailButton];
UIGraphicsEndImageContext();
I would not recommend using a UIWebView to just get a thumbnail of a YouTube video, but here is some code that I use to embed youtube videos in my app.
static NSString* EmbedHTML = "<html>\
<head>\
<meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=no, width=%0.0f\"/>\
</head>\
<iframe width=\"%0.0f\" height=\"%0.0f\" src=\"%@\" frameborder=\"0\" allowfullscreen> </iframe></html>";
Use that to embed the video and change your youtube URL from http://www.youtube.com/watch?v=T6X3j7zxUHA
to http://www.youtube.com/embed/T6X3j7zxUHA
.
Another way to get this that would not require the webview, would be to just build the thumbnail by hand. (example below)
///////////////////////////////////////////////////////////////////////////////////////////////////
-(NSString*)youtubeThumb:(NSString*)url
{
NSRange end = [url rangeOfString:@"?"];
if(end.location != NSNotFound)
{
NSRange start = [url rangeOfString:@"/" options:NSBackwardsSearch range:NSMakeRange(0, end.location)];
if(start.location != NSNotFound)
{
NSString* video_id = [url substringWithRange:NSMakeRange(start.location+1, (end.location-1)-start.location)];
return [NSString stringWithFormat:@"http://i.ytimg.com/vi/%@/2.jpg",video_id];
}
}
return nil;
}
Now you have the image thumbnail URL, just fetch it (via a simple GET
request).