Trouble in creating Webview and Button on each iCarousal View - ios

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.

Related

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

How to handle done button in UIWebview?

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.

Loading MPMovieControl for ICarousel Not Working Correctly

I am trying to achieve a iCarousel of Video URLS to allow users to see others posts.
Now i have to say i love iCarousel and this has been my only issue with it.
I have the right number of carousel objects showing up and the play button is on all of them though i'm only receiving one video at a time and the controls are not playing the video properly.
I have an NSMutableArray in place holding the _videoURLS, this is where i provide the number of carousel objects that need to be via [_videoURLS count];
In my .m file this is how i am preparing the video player with the carousel object
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
if (view == nil)
{
UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200.0f, 370.0f)];
view = mainView;
CGFloat mainViewWidth = mainView.bounds.size.width;
//Video Player View
_videoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mainViewWidth, 220)];
_videoView.backgroundColor = [UIColor colorWithRed:123/255.0 green:123/255.0 blue:123/255.0 alpha:1.0];
_videoView.center = CGPointMake(100, 170);
_videoView.tag = 7;
[view addSubview:_videoView];
//video
_player = [[MPMoviePlayerController alloc] init];
[_player.view setFrame:_videoView.bounds];
[_player prepareToPlay];
[_player setShouldAutoplay:NO];
_player.scalingMode = MPMovieScalingModeAspectFit;
_player.controlStyle = MPMovieControlStyleNone;
[_videoView addSubview:_player.view];
//Play Button
_playButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60.0f, 60.0f)];
[_playButton setBackgroundImage:[UIImage imageNamed:#"play-icon-grey.png"] forState:UIControlStateNormal];
[_playButton addTarget:self.view.superview action:#selector(postThread:) forControlEvents:UIControlEventTouchUpInside];
_playButton.center = CGPointMake(100, 160);
_playButton.tag = 3;
[view addSubview:_playButton];
}
else
{
//get a reference to the label in the recycled view
_playButton = (UIButton *) [view viewWithTag:3];
_videoView = (UIView *) [view viewWithTag:7];
}
//Setting Video For Each Carousel
for (int i = 0; i < 9; i++) {
[_player setContentURL:[NSURL URLWithString:[_videoURLS objectAtIndex:index]]];
NSLog(#"Object Link: %#",[_videoURLS objectAtIndex:index]);
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(didFinishPlaying:) name:MPMoviePlayerPlaybackDidFinishNotification object:_player];
return view;
}
It works very well if i have one object in the carousel and can handle just one video, i have to be able to handle 10 videos on the carousel and if possible have them load when its focused.
From Personal experience i feel it would be the way each item is being drawn to the screen, i just cant get my finger on the issue.
Any help is greatly appreciated!!
Per the apple documentation I found out this is not capable of being done, I have chose to use the AVFoundation Framework

iCarousel AVPlayerItem Instances not displaying correctly

What I am trying to achieve
I would like to display a carousel of videos that play independently. No more than 10 at a time. as well as having their own play button per carousel object to play independently.
What I am getting
After 3 Items display in the carousel it displays the same three over and over again until it reaches the end of the 10 items.
I am assigning the AVAsset like below:
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:[_videoURLS objectAtIndex:index]] options:nil];
_videoURLS is an NSMutableArray of NSStrings it returns a 10 count to populate 10 items in the carousel like below.
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
//return the total number of items in the carousel
return [_videoURLS count];
}
Now to populate the Video View I am doing the below:
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:[_videoURLS objectAtIndex:index]] options:nil];
//create new view if no view is available for recycling
if (view == nil)
{
//don't do anything specific to the index within
//this `if (view == nil) {...}` statement because the view will be
//recycled and used with other index values later
UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200.0f, 370.0f)];
view = mainView;
CGFloat mainViewWidth = mainView.bounds.size.width;
//Video Player View
_videoView = [[UIView alloc] initWithFrame:CGRectMake(0,0, mainViewWidth, 220)];
_videoView.backgroundColor = [UIColor colorWithRed:123/255.0 green:123/255.0 blue:123/255.0 alpha:1.0];
_videoView.center = CGPointMake(100, 170);//170
_videoView.tag = 20;
[view addSubview:_videoView];
//AV Asset Player
AVPlayerItem * playerItem = [[AVPlayerItem alloc] initWithAsset:asset];
_player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
playerLayer.frame = _videoView.bounds;
[_videoView.layer addSublayer:playerLayer];
[_player seekToTime:kCMTimeZero];
//Play Button
_playButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60.0f, 60.0f)];
[_playButton setBackgroundImage:[UIImage imageNamed:#"play-icon-grey.png"] forState:UIControlStateNormal];
[_playButton addTarget:self action:#selector(playVideo:) forControlEvents:UIControlEventTouchUpInside];
_playButton.center = CGPointMake(100, 160);
_playButton.tag = 1;
[view addSubview:_playButton];
}
else
{
//get a reference to the label in the recycled view
_playButton = (UIButton *) [view viewWithTag:1];
_videoView = (UIView *) [view viewWithTag:20];
}
//set item label
//remember to always set any properties of your carousel item
//views outside of the `if (view == nil) {...}` check otherwise
//you'll get weird issues with carousel item content appearing
//in the wrong place in the carousel
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(didFinishPlaying:) name:MPMoviePlayerPlaybackDidFinishNotification object:_player];
return view;
}
I handle the play button like below:
-(IBAction)playVideo:(id)sender {
if (_playButton.isHidden) {
[_playButton setHidden:NO];
}else{
[_playButton setHidden:YES];
[_player play];
}
}
Though when I press the play button it plays the second video in the carousel.
What is the proper way to handle this and have all the videos play single handed?

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.

Resources