How to handle done button in UIWebview? - ios

I am trying to add UIWebView in my UIViewController like this.
NSString *youTubeVideoHTML = #"<html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = 'http://www.youtube.com/player_api'; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'320', height:'568', videoId:'%#', events: { 'onLoad': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";
NSString *strYoutubeId = [arrSearchAssignmentList[indexPath.row][#"id"][#"$t"] stringByReplacingOccurrencesOfString:#"http://gdata.youtube.com/feeds/api/videos/" withString:#""];
NSString *html = [NSString stringWithFormat:youTubeVideoHTML, strYoutubeId];
videoView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
videoView.backgroundColor = [UIColor clearColor];
videoView.opaque = NO;
[self.view addSubview:videoView];
videoView.mediaPlaybackRequiresUserAction = NO;
[videoView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
Here I want to hide UIWebView when done button clicked.
So is there anyway to hide the UIWebView when the done button is clicked or how can I handle the done button in the `UIWebView when it plays a video in full screen?

When you click DONE button it will stop playing video.If you are working on NAtive app then there will be only one Webview.
Or if you are working on Hybrid app. Then there will be two Webviews. One on which you run your app and one on which you can play video.
Outside Webview show Close button on click of which you can hide the Webview.

Related

Embedding YTPlayerView In UIScrollView

I'm creating a UIScrollView that can hold images and videos from different sources. I first created and added a UIView for each image/video to the UIScrollView, then add the image/video view/layer. This works fine for images and videos using AVFoundation; however, does not work for videos using the Youtube API.
Here's my code for adding the YTPlayerView to the UIView within the UIScrollView:
YTPlayerView * youtubePlayerView = [[YTPlayerView alloc] initWithFrame: CGRectMake(0, 0, self.scrollViewWidth, self.scrollViewHeight)];
youtubePlayerView.bounds = CGRectMake(0, 0, self.scrollViewWidth, self.scrollViewHeight);
NSString * youtubePath = [media getMediaPath]; //Valid Youtube URL as NSString
NSMutableString *videoUrlCopy = [NSMutableString stringWithString:youtubePath];
NSString *vID = [videoUrlCopy lastPathComponent];
NSDictionary *playerVars = #{
#"playsinline" : #1
};
youtubePlayerView.delegate = self;
[contentView addSubview:youtubePlayerView]; //ContentView is subview of UIScrollview
[youtubePlayerView loadWithVideoId:vID playerVars:playerVars];
[youtubePlayerView playVideo];
When I try to load the youtube video with loadWithVideoId, the process terminates within YTPlayerView here: UIWebView *webView = [[UIWebView alloc] initWithFrame:self.bounds]; throwing EXC_BAD_ACCESS.
- (UIWebView *)createNewWebView {
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.bounds];
webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
webView.scrollView.scrollEnabled = NO;
webView.scrollView.bounces = NO;
return webView;
}
Interestingly, I've gotten the Youtube videos to show adding the YTPlayerView directly as a subview to self.view. Any suggestions?
I figure it out, using
pod 'youtube-ios-player-helper', :git=>'https://github.com/youtube/youtube-ios-player-helper', :commit=>'head'
instead of using pod 'youtube-ios-player-helper'
Cheers

Retrieving value of elements inside a parser object in iOS

I am working on a project which calls an API which returns an Xml data and inside my code classes are there to parse that data and extracting it to display on UI(NSXMLParser is used here).I am attaching the screen shot of xml response and the portion of code written to extract that parsed data(Parsing code I am not pasting here)
Code for extraction:
else if ([adType isEqualToString:#"textAd"])
{
NSString *html = [xml.documentRoot getNamedChild:#"htmlString"].text;
CGSize bannerSize;
if(adspaceHeight > 0 && adspaceWidth > 0)
{
bannerSize = CGSizeMake(adspaceWidth, adspaceHeight);
}
else if (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad)
{
bannerSize = CGSizeMake(728, 90);
}
else
{
bannerSize = CGSizeMake(320, 50);
}
UIWebView *webView=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, bannerSize.width, bannerSize.height)];
//load HTML string later (to avoid calling impression pixels when using custom events)
if(!headers) { //means that it's an interstitial ad
_htmlString = [NSString stringWithFormat: #"<style>*
{ -webkit-tap-highlight-color: rgba(0,0,0,0);} body {height:100%%; width:100%%;
}
img {max-width:100%%;
max-height:100%%; width:auto; height:auto; position: absolute; margin: auto; top: 0; left: 0; right: 0; bottom: 0;}
</style>
%#",html];
} else {
_htmlString = html;
}
if([skipOverlay isEqualToString:#"1"]) {
wasUserAction = NO;
webView.delegate = (id)self;
webView.userInteractionEnabled = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTapGesture:)];
[webView addGestureRecognizer:tap];
tap.delegate = self;
} else {
webView.delegate = nil;
webView.userInteractionEnabled = NO;
// add overlay later, only if no custom event is shown
}
webView.backgroundColor = [UIColor clearColor];
webView.opaque = NO;
webView.scrollView.scrollsToTop = false;
self.bannerView = webView;
}
Now for me I want to modify the same code for another xml structure...
I am pasting the screenshot of response that I have to work on.Please help me to retrieve the data inside each node.(Especially there are two links inside the "ads" tag.How to retrieve them separately).

Trouble in creating Webview and Button on each iCarousal View

I am using iCarousel for loading youtube videos.When we scroll the iCarousel respective youtube url is loaded and it plays the video.For this purpose I am using webview to load the urls.I also need one button on each Carousel view so that I can implement one action when respective carousel view is clicked even when video is loading when user taps at the carousel view it should respond to action.
Carousel Methods:
Edit:
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
return 5;
}
- (void)carouselCurrentItemIndexDidChange:(iCarousel *)carousel1
{
UIWebView *WEBPreviuos = (UIWebView *)[[carousel1 itemViewAtIndex:previousIndex] viewWithTag:2];
[WEBPreviuos loadHTMLString:nil baseURL:[[NSBundle mainBundle] resourceURL]];
previousIndex=carousel1.currentItemIndex;
UIWebView *WEB = (UIWebView *)[[carousel1 itemViewAtIndex:carousel1.currentItemIndex] viewWithTag:2];
static NSString *youTubeVideoHTML = #"<!DOCTYPE html><html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"http://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'%0.0f', height:'%0.0f', videoId:'%#', events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";
NSString *html = [NSString stringWithFormat:youTubeVideoHTML, WEB.frame.size.width, WEB.frame.size.height,#"5H9jnUqTXeQ"];
[WEB loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
}
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
UIWebView *youTubeWebView=nil;
//create new view if no view is available for recycling
if (view == nil)
{
view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 280, 180)];
view.userInteractionEnabled=YES;
((UIImageView *)view).image = [UIImage imageNamed:#"page.png"];
view.contentMode = UIViewContentModeCenter;
youTubeWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 280, 180)];
//youTubeWebView.scalesPageToFit = YES;
youTubeWebView.backgroundColor=[UIColor blackColor];
youTubeWebView.opaque=NO;
youTubeWebView.tag=2;
youTubeWebView.userInteractionEnabled=YES;
youTubeWebView.mediaPlaybackRequiresUserAction=NO;
youTubeWebView.delegate = self;
[view addSubview:youTubeWebView];
UIButton *VideoButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
VideoButton.frame=CGRectMake(0, 0, 280, 180);
VideoButton.userInteractionEnabled=YES;
VideoButton.backgroundColor=[UIColor clearColor];
[VideoButton addTarget:self action:#selector(VideoButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[youTubeWebView addSubview:VideoButton];
[view bringSubviewToFront:youTubeWebView];
}
else
{
//get a reference to the label in the recycled view
youTubeWebView=(UIWebView*) [view viewWithTag:2];
}
static NSString *youTubeVideoHTML = #"<!DOCTYPE html><html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"http://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'%0.0f', height:'%0.0f', videoId:'%#', events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";
NSString *html = [NSString stringWithFormat:youTubeVideoHTML, youTubeWebView.frame.size.width, youTubeWebView.frame.size.height,#"5H9jnUqTXeQ"];
if(index==0)
{
// label.text = [MainIndexArray objectAtIndex:index];
[youTubeWebView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
}
else
{
[youTubeWebView loadHTMLString:nil baseURL:[[NSBundle mainBundle] resourceURL]];
}
return view;
}
I am using one button below the carousel for this purpose.When I use button below the webview button is not responding.When I use button above the scrollview then the button works but the carousel is not scrolling when we drag the central view of the carousel.
So please suggest me what should I do?What I need is just an action when a respective Carousel view is clicked with webview on it.
Add a tap gesture to the image view (and be sure to set userInteractionEnabled = YES on the image view). This is simpler than using a button which will interfere with other interactions.
The gesture will also interfere, so you will need to update the carousel so that the gestures that it uses internally can work at the same time as the new gesture. This is done using the gesture delegate methods.

iAd like popup view in ios app

i am trying to develop a app that will load a iAd like popup view that will show a webview with a image in it. what i mean is that it will load a JPG or PNG url in it. i successfully created that popup but webview in not showing image in it can anyone please debug my code. i will post it here.
MainViewController.m
-(IBAction)openPopupWithURL
{
[MTPopupWindow showWindowWithHTMLFile:#"http://URL/ad.php" insideView:self.view];
}
PopUpWindow.h
#import <Foundation/Foundation.h>
#interface MTPopupWindow : NSObject
{
UIView* bgView;
UIView* bigPanelView;
}
+(void)showWindowWithHTMLFile:(NSString*)fileName insideView:(UIView*)view;
#end
PopUpWindow.m
#import "MTPopupWindow.h"
#define kShadeViewTag 1000
#interface MTPopupWindow(Private)
- (id)initWithSuperview:(UIView*)sview andFile:(NSString*)fName;
#end
#implementation MTPopupWindow
/**
* This is the only public method, it opens a popup window and loads the given content
* #param NSString* fileName provide a file name to load a file from the app resources, or a URL to load a web page
* #param UIView* view provide a UIViewController's view here (or other view)
*/
+(void)showWindowWithHTMLFile:(NSString*)fileName insideView:(UIView*)view
{
[[MTPopupWindow alloc] initWithSuperview:view andFile:fileName];
}
/**
* Initializes the class instance, gets a view where the window will pop up in
* and a file name/ URL
*/
- (id)initWithSuperview:(UIView*)sview andFile:(NSString*)fName
{
self = [super init];
if (self) {
// Initialization code here.
bgView = [[[UIView alloc] initWithFrame: sview.bounds] autorelease];
[sview addSubview: bgView];
// proceed with animation after the bgView was added
[self performSelector:#selector(doTransitionWithContentFile:) withObject:fName afterDelay:0.1];
}
return self;
}
/**
* Afrer the window background is added to the UI the window can animate in
* and load the UIWebView
*/
-(void)doTransitionWithContentFile:(NSString*)fName
{
//faux view
UIView* fauxView = [[[UIView alloc] initWithFrame: CGRectMake(10, 10, 200, 200)] autorelease];
[bgView addSubview: fauxView];
//the new panel
bigPanelView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, bgView.frame.size.width, bgView.frame.size.height)] autorelease];
bigPanelView.center = CGPointMake( bgView.frame.size.width/2, bgView.frame.size.height/2);
//add the window background
UIImageView* background = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"popupWindowBack.png"]] autorelease];
background.center = CGPointMake(bigPanelView.frame.size.width/2, bigPanelView.frame.size.height/2);
[bigPanelView addSubview: background];
//add the web view
int webOffset = 10;
UIWebView* web = [[[UIWebView alloc] initWithFrame:CGRectInset(background.frame, webOffset, webOffset)] autorelease];
web.backgroundColor = [UIColor clearColor];
if ([fName hasPrefix:#"http"]) {
//load a web page
web.scalesPageToFit = YES;
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: fName]]];
} else {
//load a local file
NSError* error = nil;
NSString* fileContents = [NSString stringWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fName] encoding:NSUTF8StringEncoding error: &error];
if (error!=NULL) {
NSLog(#"error loading %#: %#", fName, [error localizedDescription]);
} else {
[web loadHTMLString: fileContents baseURL:[NSURL URLWithString:#"file://"]];
}
}
[bigPanelView addSubview: web];
//add the close button
int closeBtnOffset = 10;
UIImage* closeBtnImg = [UIImage imageNamed:#"popupCloseBtn.png"];
UIButton* closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[closeBtn setImage:closeBtnImg forState:UIControlStateNormal];
[closeBtn setFrame:CGRectMake( background.frame.origin.x + background.frame.size.width - closeBtnImg.size.width - closeBtnOffset,
background.frame.origin.y ,
closeBtnImg.size.width + closeBtnOffset,
closeBtnImg.size.height + closeBtnOffset)];
[closeBtn addTarget:self action:#selector(closePopupWindow) forControlEvents:UIControlEventTouchUpInside];
[bigPanelView addSubview: closeBtn];
//animation options
UIViewAnimationOptions options = UIViewAnimationOptionTransitionFlipFromRight |
UIViewAnimationOptionAllowUserInteraction |
UIViewAnimationOptionBeginFromCurrentState;
//run the animation
[UIView transitionFromView:fauxView toView:bigPanelView duration:0.5 options:options completion: ^(BOOL finished) {
//dim the contents behind the popup window
UIView* shadeView = [[[UIView alloc] initWithFrame:bigPanelView.frame] autorelease];
shadeView.backgroundColor = [UIColor blackColor];
shadeView.alpha = 0.3;
shadeView.tag = kShadeViewTag;
[bigPanelView addSubview: shadeView];
[bigPanelView sendSubviewToBack: shadeView];
}];
}
/**
* Removes the window background and calls the animation of the window
*/
-(void)closePopupWindow
{
//remove the shade
[[bigPanelView viewWithTag: kShadeViewTag] removeFromSuperview];
[self performSelector:#selector(closePopupWindowAnimate) withObject:nil afterDelay:0.1];
}
/**
* Animates the window and when done removes all views from the view hierarchy
* since they are all only retained by their superview this also deallocates them
* finally deallocate the class instance
*/
-(void)closePopupWindowAnimate
{
//faux view
__block UIView* fauxView = [[UIView alloc] initWithFrame: CGRectMake(10, 10, 200, 200)];
[bgView addSubview: fauxView];
//run the animation
UIViewAnimationOptions options = UIViewAnimationOptionTransitionFlipFromLeft |
UIViewAnimationOptionAllowUserInteraction |
UIViewAnimationOptionBeginFromCurrentState;
//hold to the bigPanelView, because it'll be removed during the animation
[bigPanelView retain];
[UIView transitionFromView:bigPanelView toView:fauxView duration:0.5 options:options completion:^(BOOL finished) {
//when popup is closed, remove all the views
for (UIView* child in bigPanelView.subviews) {
[child removeFromSuperview];
}
for (UIView* child in bgView.subviews) {
[child removeFromSuperview];
}
[bigPanelView release];
[bgView removeFromSuperview];
[self release];
}];
}
#end
and this is output
My ad.php
<?php
include("../includes/opencon.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Mobile Ad</title>
</head>
<body>
<?php
$setting = mysql_fetch_object(mysql_query("select * from my_settings where id=1"));
?>
<img src="http://url.com/media/<?=$setting->image?>" style="width:100%; height:auto;"/>
</body>
</html>
Please provide additional information, whether this happens when loading a local or remote image. I think for local images you could adjust your base url of the webview.
If you want to load local images, please provide the base URL of the App bundle:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];
So instead of:
[web loadHTMLString: fileContents baseURL:[NSURL URLWithString:#"file://"]];
use the app bundle url:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[web loadHTMLString: fileContents baseURL:baseURL];
For further debugging, you could set the webview's delegate to your view and check, what the webview's content looks like:
web.delegate = self;
To now use the delegate implement the following:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *html = [webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"];
NSLog(#"%#",html);
}
Alternatively, go to Safari->Develop->iPhone Simulator/iOS Device->Webview
And take a look at the source code in the debug console of safari.

Unable to load full Facebook comment plugins inside an iOS UIWebView

I have a simple ViewController to load FB comments plugins inside a UIWebView
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320.0f, 1505.0f)];
NSString * html = #"\
<!DOCTYPE html>\
<html xmlns:fb='http://ogp.me/ns/fb#'>\
<head>\
<meta name='viewport' content='width=device-width, initial-scale=1.0'>\
</head>\
<body style='background-color:red;'>\
\
<div id='fb-root'></div>\
<script>(function(d, s, id) {\
var js, fjs = d.getElementsByTagName(s)[0];\
if (d.getElementById(id)) return;\
js = d.createElement(s); js.id = id;\
js.src = 'http://connect.facebook.net/en_US/all.js#xfbml=1&appId=xxx';\
fjs.parentNode.insertBefore(js, fjs);\
}(document, 'script', 'facebook-jssdk'));</script>\
\
<fb:comments href='http://example.com' num_posts='10'></fb:comments>\
\
</body>\
</html>\
";
[webView loadHTMLString:html baseURL:nil];
[self.view addSubview:webView];
I can see the comments being loaded, but just the height is strange, seems auto resize failed? I can view the whole comments if I am using mobile safari.
you can use this code for displaying the fb comment in iOS UIWebview
UIWebView *fbWebview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 1505)];
[fbWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"https://www.facebook.com/Levis"]]];
CGRect scrollViewFrame = CGRectMake(0, 0, 320, 1024);
UIScrollView *scrollViewMain = [[UIScrollView alloc] initWithFrame:scrollViewFrame];
CGSize scrollViewContentSize = CGSizeMake(320, 1505);
[scrollViewMain setContentSize:scrollViewContentSize];
[scrollViewMain setBounces:NO];
[scrollViewMain setScrollEnabled:YES];
[scrollViewMain setShowsVerticalScrollIndicator:YES];
[scrollViewMain setBackgroundColor:[UIColor redColor]];
[scrollViewMain addSubview:fbWebview];
[self.view addSubview:scrollViewMain];
instead of "https://www.facebook.com/Levis" use your FB URL
this may help you
You need to specify a baseURL
[webView loadHTMLString:html baseURL:[NSURL URLWithString:#"http://www.example.com"]];
#Howard you can use http://www.facebook.com/plugins/comments.php?href=http://www.google.com' scrolling='yes' profile='yes' frameborder='0' style='border:none; overflow:hidden; width:300px; height:30px;' data-href='http://www.google.com' allowTransparency='true'>"
Same problem here. The solution was not to use a local HTML file (or HTML string). Upload the HTML file to an server and use:
NSURL *url = [NSURL URLWithString:#"http://www.blablblab.com/yourfile.html"];
[self.webview loadRequest:[NSURLRequest requestWithURL:url]];
instead of:
[self.webview loadHTMLString:localString baseURL:nil];
I didn't discovered yet why there is a difference in the layout when the file is on a server, but when it is a local file, the height of my Facebook Comments View was always reduced to "height:160". Apparently it's because of the "all.js" facebook script (accordingly to this question).

Resources