Get notification when play button appears in embedded video with UIWebView - iphone

i'm using webviews into my app to embed videos, in this way
NSString *embedHTML = #"<iframe width=\"300\" height=\"250\" src=\"http://www.youtube.com/.....\" frameborder=\"0\" allowfullscreen></iframe>";
NSString *html = [NSString stringWithFormat:embedHTML];
[_webView loadHTMLString:html baseURL:nil];
I'd like to get notified when the play button appears, in order to create and stop an activity indicator... I've used
- (void)webViewDidFinishLoad:(UIWebView *)webView
but it's not sufficient... when the webview finishes loading and the activity indicator stops, the playbutton appears 2-3 seconds later...
How can i synchronize the activityindicator stop with the playbutton appearance?
Thanks

Related

Youtube video in UIWebview not working

Using this code to play YouTube video in UIWebView
- (void)embedYouTube {
UIWebView *webView = [[[UIWebView alloc] initWithFrame:self.view.bounds] autorelease];
webView.autoresizesSubviews = YES;
webView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
// iframe
videoHTML = [NSString stringWithFormat:#"\
<html>\
<head>\
<style type=\"text/css\">\
iframe {position:absolute; top:50%%; margin-top:-130px;}\
body {background-color:#000; margin:0;}\
</style>\
</head>\
<body>\
<iframe width=\"560%%\" height=\"315px\" src=\"%#\"http://www.youtube.com/embed/j9CukQje2qw\" frameborder=\"0\" allowfullscreen></iframe>\
</body>\
</html>", videoURL];
[videoView loadHTMLString:videoHTML baseURL:nil];
}
When i click on this LaunchVideo UIButton all it shows black screen on iOS device
-(void)LaunchVideo:(id)sender
{
self.videoURL = #"http://www.youtube.com/embed/j9CukQje2qw";
WebViewController *webViewController = [[[WebViewController alloc] initWithNibName:nil bundle:nil] autorelease];
webViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
webViewController.videoURL = self.videoURL;
[self presentModalViewController:webViewController animated:YES];
}
If anyone can point out what i m missing or doing wrong in this code. Why youtube video is not showing. Not using interface builder doing programmtically. Got this project code from web. Tried this project code on ios device it works fine for that project but when applied its code in my project then it is not working. Only difference that his projectcode from web uses interface builder and i am doing it programmtically.I dont get it.
Please help what is wrong with this code.
Thanks for help.
Here is another way to load the youtube video into your app. First, put a UIWebView into your interface and size it to how big you want the video should show (there will be a button to make it full screen), then make an IBOutlet to it, so you can change its properties of hidden (to make it pop up and go away) Here is some code. In the code there is a method used called webviewshow, this calls a simple method that basically just says
webview.hidden = NO;
webviewbutton.hidden = NO;
Then there is a button that also pops up that makes the web view go away when tapped. Here is the code to load the youtube video into the web view
// Create your query ...
NSString* searchQuery = [NSString stringWithFormat:#"http://www.youtube.com/embed/j9CukQje2qw];
// Be careful to always URL encode things like spaces and other symbols that aren't URL friendly
searchQuery = [searchQuery stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
// Now create the URL string ...
NSString* urlString = searchQuery;
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
[webView loadRequest:request]; currentTimer= [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(webviewshow) userInfo:nil repeats:NO];;
It waits 2 seconds (usual wait time for most connections) until the web view is shown, so the page is loaded and the user does not have to watch it load.
Then when you want to make the video go away, make a method to close the web view like so
- (void) makewebviewGoAway {webview.hidden = YES; webviewbutton.hidden = YES;}
Hopefully, that was helpful. IF you need further help or explanation, just comment off of this.

How to play video from URL in Ipad?

In my application i get the links of video from server in UITableview .all these link are store on Sever in Textfile,i get all these link from sever one by one and assign each to cell in UITableview.all these i done succefully but i want when i click on any cell in UITableview its play the video in next view.here is my code.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
nextview *dvController = [[nextview alloc] initWithNibName:#"nextview" bundle:nil];
[self presentModalViewController:dvController animated:YES];
strFile = [Listdata objectAtIndex:indexPath.row];
NSLog(#"test=%#",strFile);
[dvController release];
}
and in next view i assign the link which i store in "strFile" to MPMoviePlayerController here is my code.
-(void)viewDidAppear:(BOOL)animated
{
NSLog(#"mytest=%#",strFile);
NSURL *url = [NSURL URLWithString:strFile];
NSLog(#"myurl=%#",url);
myplayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
myplayer.view.frame = CGRectMake(0, 0,900, 700);
[self.view addSubview:myplayer.view];
[myplayer play];
}
In NSlog i see the link but its not play in MPMoviePlayerController.Any one can guide me that what mistake i make.thanx in advance.
#prince : can u tell me what url you are getting in NSLog?? i think u're mistaken in getting the url.
we can get url either by
url = [NSURL fileURLWithPath:strUrl];
else
url = [NSURL URLWithString:strUrl];
try it out once.
You probably shouldn't be setting the frame and adding to the subview, You may be confused with MPMoviePlayerViewController. Try this...
-(void)viewDidAppear:(BOOL)animated {
NSLog(#"mytest=%#",strFile);
NSURL *url = [NSURL URLWithString:strFile];
NSLog(#"myurl=%#",url);
myplayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
myplayer.scalingMode = MPMovieScalingModeAspectFill;
[myplayer play];
}
EDIT disregard my code, you can't directly play a YouTube video in MPMoviePlayerController. Check this Post instead Play YouTube videos with MPMoviePlayerController instead of UIWebView
to youtube video play inside app is to create a UIWebView with the embed tag from Youtube for the movie you want to play as the UIWebView's content. UIWebView will detect that the embedded object is a Youtube link, and the web view's content will be the youtube preview for the video. When your user clicks the preview, the video will be shown in an MPMoviePlayerController. try this link:
http://iphoneincubator.com/blog/audio-video/how-to-play-youtube-videos-within-an-application
Unfortunately, there's no way to directly play a youtube video with MPMoviePlayerController because youtube does not expose direct links to the video files.

Can't play video using webview

I am using webview to show the video thumb in my application, all is working fine and I can see the video thumb there in my application. But when I tap on the webview It shows loading the video but movie player never shown in my application and status bar disappears. but when I use same code in another sample application, it plays the video successfully. I am not able to find the issue. Here is my code segment
NSString *vimeoURL = [NSString stringWithFormat:#"http://player.vimeo.com/video/%#?title=0&byline=0&portrait=0", [stepDic objectForKey:video_id]];
NSString *htmlStr = [NSString stringWithFormat:#"<iframe src=\"%#\" width=\"100\" height=\"100\" frameborder=\"0\" webkitAllowFullScreen allowFullScreen></iframe>", vimeoURL];
[aWebView loadHTMLString:htmlStr baseURL:nil];
[self.view addSubview:aWebView];

Loading a document into a Webview

Am trying to load a .docx file into the uiwebview and am displaying it.To load the document into the webview it takes some fraction of seconds so i can see a white blank screen before the content can appear on the screen.I don't want to see that white screen while loading instead of that i want to do some actions like activity indicator or changing the background.How can i achieve this please help me.
Here is my code;
-(void)loadDocument:(NSString*)documentName inView:(UIWebView*)webViews
{
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 416)];
isWebviewLoaded=YES;
webView.delegate=self;
webView.alpha=0;
NSString *path = [[NSBundle mainBundle] pathForResource:#"SKIN ADVISORuser_updated.docx" ofType:nil];
//NSString *path = [[NSBundle mainBundle]pathForResource:#"UserGuidelines3.html" ofType:nil];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webViews loadRequest:request];
}
and in viewdidload am calling above method:
[self loadDocument:#"ADVISORuser_updated.docx" inView:self.webView];
Even am implementing a delegate method to change the background but delegate is not executing
- (void)webViewDidFinishLoad:(UIWebView *)webViewload {
if (isWebviewLoaded)
{
isWebviewLoaded = NO;
webView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:#"Instructions Screen Background light_PNG.png"]];
[UIView beginAnimations:#"webView" context:nil];
webView.alpha = 1.0;
[UIView commitAnimations];
}
}
Please can anyone help me..
before loadRequest u could create UIActivityIndicator object and start it by calling start method
and in webView delegate didFinishLoading: & didFailwithError method suspend the activity indicator
- (void)webViewDidFinishLoad:(UIWebView *)webViewload {
will be called only if you have set the delegate for the webView (in the xib &.h file)

UIWebView loading parsed html string

i'm building an app that will display some newsletters to the users. the newsletters are displayed in a uiWebView. I'm reading the url's for the newsletters from an rss feed. I parse the xml, and in a table view i have all the newsletters. When a cell is clicked the uiWebView is pushed and the newsletter is loaded. Because the uiWebView doesn't open links that have target=_blank i need to replace the _blank from target with "". In an NSOperation i download the contents of the html and after the download is finished i replace the strings like this:
NSMutableString *page = [[[NSMutableString alloc] initWithData:pageData encoding:NSISOLatin1StringEncoding] autorelease]; [page replaceOccurrencesOfString:#"target=_blank" withString:#"target=""" options:0 range:NSMakeRange(0, [page length])];
after i do this i load the parsed string in the webView to display it to the user.
[myWebView loadHTMLString:page baseURL:[NSURL URLWithString:#""]];
while the NSOperation is downloading the contents of the page an HUD with a activity indicator and a label that says Loading is showed. When the download is finished the HUD is removed from the superview.
so far so good..but here come the questions. i used the NSOperation with the callback function because i wasn't able to determine the last call to webDidFinishLoading ( i read this UIWebView - How to identify the "last" webViewDidFinishLoad message? - this is a part of my problem but the response was to use some Apple private classes and that is a problem for me). so i'm doing this:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = request.URL;
NSString *urlString = url.absoluteString;
NSLog(#"WebViewSouldStartWithRequest: %#", urlString);
if (navigationType == UIWebViewNavigationTypeLinkClicked)
{
if(![urlString isEqualToString:#"about:blank"])
{
NSLog(#"FeedViewController: startPageLoad");
activityHud = [[HUDView alloc] initWithFrame:CGRectMake(110, 100, 80, 80)];
[activityHud setText:#"Loading"];
[myWebView addSubview:activityHud];
NSLog(#"FeedViewController: pageUrl = %#", urlString);
[self resetWebView];
[urlLoader loadPageFromUrl:request.URL withCallbackTarget:self withCallbackSelector:#selector(endLoading:)];
}
}
return NO;
}
- (void) endLoading:(NSMutableString *)page { [self resetWebView]; NSLog(#"FeedViewController: endLoading"); [activityHud removeFromSuperview]; [myWebView loadHTMLString:page baseURL:[NSURL URLWithString:#""]]; }
after i touch a cell in the table view and the newsletter is showed it looks like it should, when i click a link in the newsletter, the page is loaded with the new request, parsed but visually is not looking as it should (i looked at the page after parsing in NSLog and it has the css styles and html tags, head, body opened and closed correctly) anyone had this problem with uiWebView, not showing webpages correctly?
i tried loading the page with - (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType{ return YES; }
and in - (void)webViewDidFinishLoad:(UIWebView *)webview {} and in - webViewDiStartLoad
but the methods are being called for every item that is loaded in the webview so showing and hiding the HUD in those method is not a good solution.
I encountered some problems while using - (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType { ... return NO }
for example links that have paths like this /bilder-galerien to not work and in NSLog i receive this for them
Unknown scheme, doing nothing:
/bilder-galerien
but when i use
(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType { return Yes } and didstartLoading and finishLoading the urls are loaded and i don't know why...
another problem are the special german characters..in my first load(after pressing a cell in the uiTableView) the page is parsed like it should be by the uiWebView but after i click a link and the corresponding request is loaded also the characters are not parsed correctly..
can anyone point me in the good direction? thank you in advance
UIWebView doesn't open target="_blank" links. Certain links don't fire UIWebViewNavigationTypeLinkClicked events. This happens when the link has the target="_blank" attribute.
To work around this problem i used the code below. It injects some javascript after the page load to remove the target attribute from all the links. After using this code i didn;t needed anymore to parse the html source and replace _blank with _self for example.
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *js = #"\
var d = document.getElementsByTagName('a');\
for (var i = 0; i < d.length; i++) {\
if (d[i].getAttribute('target') == '_blank') {\
d[i].removeAttribute('target');\
}\
}\
";
[webView stringByEvaluatingJavaScriptFromString:js];
}
I like SorinA answer, we can make it even better by:
avoid obstructing javascript with var d
as we know we're running webkit engine we can use selectors:
...so in your UIWebViewDelegate protocol method invoke js code:
- (void) webViewDidFinishLoad: (UIWebView *) webView {
[webView stringByEvaluatingJavaScriptFromString: #"(function($){for(var i=0;i<$.length;++i){$[i].removeAttribute('target')}})(document.querySelectorAll('a[target=_blank]'))"];
}