Custom Advert banner - iphone

I have spent a while looking around but cant seem to find much on the subject. I would like to make a banner like iAd's but for my own in-app adverts. The adverts will take the user to a view within the app.
Here is a design that I have made to show the ad banners.
This is what I have managed to implement so far.
I have two problems with what I have done so far.
1) I would like to customise the order of the images.
I would like a main ad then sub ad's. The main add should play first and every other image should be the main ad. Then the sub ad's should be in a random order.
How could I achieve this? Could I do it with the current way im animation it or would there be a better solution?
2) I do not know how to link the images to different places.
So far I have it so all the images run the same action. How can I make them change to different views?
This Is what I have so far .
#implementation SponsorBannerView{
}
#synthesize bannerImage;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect{
//get the sponsors banners and id's.
DataBase * dataBase = [[DataBase alloc] init];
[dataBase openDB];
NSMutableDictionary *BannersAndId = [dataBase getBanners];
NSLog(#"banner and id's : %#",BannersAndId);
//create an id array and a banner array.
self.poiIDs = [BannersAndId allKeys];
self.banners = [BannersAndId allValues];
//get the root file path for the images
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//create an array to hold the image
NSMutableArray * images = [[NSMutableArray alloc]init];
//create an array containing all the images
for (int i = 0; i<self.banners.count; i++) {
NSString *tmp = [NSString stringWithFormat:#"%#/%#",documentsDirectory, self.banners[i]];
UIImage * tmpIamge = [UIImage imageWithContentsOfFile:tmp];
[images addObject:tmpIamge];
}
//cast the mutable array into an array
NSArray *array = [NSArray arrayWithArray:images];
//set all the banner settings
bannerImage=[[UIImageView alloc]init];
bannerImage.frame=CGRectMake(0, 0, 320, 50);
bannerImage.backgroundColor=[UIColor purpleColor];
[bannerImage setAnimationImages:array];
[bannerImage setAnimationDuration:6];
[bannerImage setAnimationRepeatCount:0];
[bannerImage startAnimating];
//add to view.
[self addSubview:bannerImage];
// add a uibutton on top of the uiimageview and assign an action for it
UIButton* actionButton=[UIButton buttonWithType:UIButtonTypeCustom];
actionButton.frame=CGRectMake(0, 0, 320, 50);
[actionButton addTarget:self action:#selector(sponsorBannerAction) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:actionButton];
}
-(void) sponsorBannerAction{
// do what ever here like going to an other uiviewController as you mentionned
NSLog(#"Pressed");
}
This is a view that I have added as a sub view of my main view.
Any help would be wonderful.
Thanks

Will you will want to have two arrays one for images, the other for link targets.
ex. img1, img2, img3 and img1ClickedMethod, img2ClickedMethod, img3ClickedMethod
When you swap your images in your button, also change the target of the button clicks to the new method.
i.e. [actionButton addTarget:self action:#selector(img1ClickedMethod) forControlEvents:UIControlEventTouchUpInside]; changes to [actionButton addTarget:self action:#selector(img2ClickedMethod) forControlEvents:UIControlEventTouchUpInside];
- (void)nextImageFade{
NSArray *imgArray;
imgArray = [NSArray arrayWithObjects:
#"img1.jpg",
#"img2.jpg",
#"img3.jpg",
nil];
NSArray *methodArray;
imgArray = [NSArray arrayWithObjects:
#"clicked1",
#"clicked2",
#"clicked2",
nil];
UIImage *image1 = [UIImage imageNamed:[imageArray objectAtIndex:currentImg]];
if(currentImg < [imgs count]-1){
currentImg++;
}else{
currentImg = 0;
}
UIImage *image2 = [UIImage imageNamed:[imgArray objectAtIndex:currentImg]];
CABasicAnimation *crossFade = [CABasicAnimation animationWithKeyPath:#"contents"];
crossFade.delegate = self;
crossFade.duration = 0.5;
crossFade.fromValue = (id)image1.CGImage;
crossFade.toValue = (id)image2.CGImage;
[_imgView1.layer addAnimation:crossFade forKey:#"animateContents"];
_imgView1.image = image2;
//This this may work for changing targets
[actionButton addTarget:self action:#selector([methodArray objectAtIndex:CurrentImg]) forControlEvents:UIControlEventTouchUpInside];
if(nextImgTimer != nil){
[nextImgTimer invalidate];
}
nextImgTimer = [NSTimer scheduledTimerWithTimeInterval:5
target:self
selector:#selector(nextImageFade)
userInfo:nil
repeats:NO];
}

Related

save image from Scroll view

help please. I have this code that shows me images in scrollview.:
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *imgNames = [[NSArray alloc] initWithObjects:#"ip1.jpg", #"ip2.jpg", #"ip3.jpg", #"ip4.jpg", #"ip5.jpg", #"ip6.jpg", #"ip7.jpg", #"ip8.jpg", #"ip9.jpg", #"ip10.jpg",#"ip11.jpg",#"ip12.jpg",#"ip13.jpg",#"ip14.jpg",#"ip15.jpg",#"ip16.jpg",#"ip17.jpg",#"ip18.jpg",#"ip19.jpg",#"ip20.jpg",#"ip21.jpg", nil];
// Setup the array of UIImageViews
NSMutableArray *imgArray = [[NSMutableArray alloc] init];
UIImageView *tempImageView;
for(NSString *name in imgNames) {
tempImageView = [[UIImageView alloc] init];
tempImageView.contentMode = UIViewContentModeScaleAspectFill;
tempImageView.image = [UIImage imageNamed:name];
[imgArray addObject:tempImageView];
}
CGSize pageSize = scrollViewBack.frame.size; // scrollView is an IBOutlet for our UIScrollView
NSUInteger page = 0;
for(UIView *view in imgArray) {
[scrollViewBack addSubview:view];
// This is the important line
view.frame = CGRectMake(pageSize.width * page++ + 40, 0, pageSize.width - 80, pageSize.height);
}
scrollViewBack.contentSize = CGSizeMake(pageSize.width * [imgArray count], pageSize.height);
}
Now, I want a UILabel, that will show me, Image name, when I will scroll. Help me please, I can't implement that. Thanks a lot.
In your second for loop you can acces to the indexes of the objects of imgArray and imgNames, so try this:
int idx = [imgArray indexOfObject:view];
NSString *strName = [imgNames objectAtIndex:idx];
//create the label
label.text=strName;
//add the label in the scrollView
If you want to show the label just when the new image is showed, keep the two arrays as iVars and use UIPageControl to track in wich page of the scrollview you are. (Sample code).
In your loop you could do something like this. Read the apple docs. Search google for how to make a label. Its not hard to learn this stuff if you just try.
for(NSString *name in imgNames) {
// ....
UILabel *label = [[UILabel alloc] initWithFrame:WHEREYOUWANTIT];
[label setText:name];
}

Subclassed UIView not displaying UIImageViews added to it

So I have class called CSImageViews (subclass of uiview), that is essentially a row of UIImageViews enclosed in a single subclassed UIView.
I've added a custom init method like so (node/yaml contains uiimage name data):
- (id)initWithFrame:(CGRect)frame withNode:(NSDictionary *)node
{
self = [super initWithFrame:frame];
if (self) {
_node = node;
_imageViewYAML = [node objectForKey:#"items"];
_imageViews = [self getImageViewsForItems:_imageViewYAML];
}
return self;
}
And my getImageViewsforItems is like so (adds them all to subview):
-(NSArray *)getImageViewsForItems:(NSArray *)items
{
NSMutableArray *ivs = [NSMutableArray arrayWithCapacity:[items count]];
for (int i = 0; i < [items count]; i++) {
NSDictionary *item = [items objectAtIndex:i];
NSString *type = [item objectForKey:#"type"];
NSString *name = [item objectForKey:#"name"];
UIImage *image = [UIImage imageNamed:name];
UIImageView *iv = [[UIImageView alloc] init];
iv.image = image;
iv.tag = i;
[ivs addObject:iv];
[self addSubview:iv];
}
return ivs;
}
Now when I add this custom view to my main view like this nothing happens:
CSImageViews *imageViews = [[CSImageViews alloc] initWithFrame:frame withNode:node];
[view addSubview:imageViews];
But if I add this 'csimageviews' container into a new uiview first it appears:
CSImageViews *imageViews = [[CSImageViews alloc] initWithFrame:frame withNode:node];
UIView *v = [[UIView alloc] initWithFrame:frame];
[v addSubview:imageViews];
[view addSubview:v];
thoughts?
Stupid error by me. In this particular subclassed UIView I have a method that was called every time its parent view controller was shown. This method actually removed all subviews from the view... so I wasn't able to see the uiimageviews when I rendered it in the initial view... doh.

How to download multiple images of table view cell in background?

i want to create an application in one row of tableView there will be 4 images of button which will be loaded from server in background because if i directly load them than the table view will hang some. for this i have used this code for creating button in cell and performing to download images in background.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *hlCellID = #"hlCellID";
UITableViewCell *hlcell = [tableView dequeueReusableCellWithIdentifier:hlCellID];
if(hlcell == nil) {
hlcell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:hlCellID] autorelease];
hlcell.accessoryType = UITableViewCellAccessoryNone;
hlcell.selectionStyle = UITableViewCellSelectionStyleNone;
}
int section = indexPath.section;
NSMutableArray *sectionItems = [sections objectAtIndex:section];
int n = [sectionItems count];
int i = 0, j = 0, tag = 1;
int x = 10;
int y = 30;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for (i = 1; i<= n ; i++) //[arr count]
{
for(j=1; j<=4;j++)
{
if (i>=n) break;
Item *item = [sectionItems objectAtIndex:i];
CGRect rect = CGRectMake(x = x, y = y, 68, 65);
UIButton *button=[[UIButton alloc] initWithFrame:rect];
[button setFrame:rect];
UIImage *buttonImageNormal=[UIImage imageNamed:item.image];
[button setBackgroundImage:buttonImageNormal forState:UIControlStateNormal];
[button setContentMode:UIViewContentModeCenter];
// set the image to be loaded (using the same one here but could/would be different)
NSURL *imgURL = [NSURL URLWithString:#"http://londonwebdev.com/wp-content/uploads/2010/07/featured_home.png"];
// Create an array with the URL and imageView tag to
// reference the correct imageView in background thread.
NSMutableArray *arr = [[NSArray alloc] initWithObjects:imgURL, [NSString stringWithFormat:#"%d", tag], nil ];
// Start a background thread by calling method to load the image
[self performSelectorInBackground:#selector(loadImageInBackground:) withObject:arr];
// button.tag = [tagValue intValue];
button.tag = tag;
//NSLog(#"....tag....%d", button.tag);
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[hlcell.contentView addSubview:button];
[button release];
tag++;
x = x + 77;
}
x = 10;
y = y + 74;
}
[pool release];
return hlcell;
}
the above code work perfectly but when i download the images and trying to assign at the some particular button than i can't find the button tags althoug i can find the button tags while touchupinside action.
- (void) loadImageInBackground:(NSArray *)urlAndTagReference {
NSLog(#"Received URL for tagID: %#", urlAndTagReference);
// Create a pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Retrieve the remote image. Retrieve the imgURL from the passed in array
NSData *imgData = [NSData dataWithContentsOfURL:[urlAndTagReference objectAtIndex:0]];
UIImage *img = [[UIImage alloc] initWithData:imgData];
// Create an array with the URL and imageView tag to
// reference the correct imageView in background thread.
NSMutableArray *arr = [[NSArray alloc] initWithObjects:img, [urlAndTagReference objectAtIndex:1], nil ];
// Image retrieved, call main thread method to update image, passing it the downloaded UIImage
[self performSelectorOnMainThread:#selector(assignImageToImageView:) withObject:arr waitUntilDone:YES];
[pool release];
}
- (void) assignImageToImageView:(NSArray *)imgAndTagReference
{
// Create a pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int i;
UIButton *checkView;
// [imagesForCategories addObject:[imgAndTagReference objectAtIndex:1]];
// UITableViewCell *cell = [celebCategoryTableView cellForRowAtIndexPath:[imgAndTagReference objectAtIndex:1]];
// UIImageView *profilePic = (UIImageView *)[cell.contentView viewWithTag:20];
// profilePic.image = [imgAndTagReference objectAtIndex:0];
// checkView.tag = [[imgAndTagReference objectAtIndex:1] intValue];
// loop
for (UIButton *checkView in [self.tblImage subviews] )
{ i++;
NSLog(#"Checking tag: %d against passed in tag %d",checkView.tag, [[imgAndTagReference objectAtIndex:1] intValue]);
if ([checkView tag] == [[imgAndTagReference objectAtIndex:1] intValue]) {
if (i==35) break;
// Found imageView from tag, update with img
// [checkView setImage:[imgAndTagReference objectAtIndex:0]];
[checkView setImage:[imgAndTagReference objectAtIndex:0] forState:UIControlStateNormal];
//set contentMode to scale aspect to fit
checkView.contentMode = UIViewContentModeScaleAspectFit;
//change width of frame
CGRect frame = checkView.frame;
frame.size.width = 80;
checkView.frame = frame;
}
}
// release the pool
[pool release];
// Remove the activity indicator created in ViewDidLoad()
[self.activityIndicator removeFromSuperview];
}
the all code works perfect but i can't find the table cell subview here for (UIButton *checkView in [self.tblImage subviews] so how to find the subviews of table cell subviews.?
i want to create something like this pls see image.! after that new city will come and just section change the data will show new images in row and cell section.
you may use SDWebImage
Web Image
This library provides a category for UIImageVIew with support for remote images coming from the web.
It provides:
An UIImageView category adding web image and cache management to the Cocoa Touch framework
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
Performances!
just use it
[youImageView setImageWithURL:[NSURL URLWithString:url] placeholderImage:nil options:SDWebImageRetryFailed];

parsing json and showing in grid view

I m parsing a json url and showing it in a grid view.The output in the simulator looks like a grid of images similar to imagepicker.on pressing the image it got to navigate to a new view...the code works fine and i am able to receive the data in the console when the image is clicked.the problem is i m not able to navigate to the next view..cud u guys help me out
- (void)viewDidLoad {
[super viewDidLoad];
jsonurl=[NSURL URLWithString:#"http://www.1040communications.net/sheeba/stepheni/iphone/stephen.json"];
jsonData=[[NSString alloc]initWithContentsOfURL:jsonurl];
jsonArray = [jsonData JSONValue];
items = [jsonArray objectForKey:#"items"];
// NSLog(#"hello:%#",items);
story = [[NSMutableArray array]retain];
media1 = [[NSMutableArray array]retain];
for (NSDictionary *item in items )
{
[story addObject:[item objectForKey:#"title"]];
[media1 addObject:[item objectForKey:#"media"]];
}
UIScrollView *view = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
int row = 0;
int column = 0;
for(int i = 0; i < media1.count; i++) {
NSString *mel=[media1 objectAtIndex:i];
NSString *escapedURL = [mel stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
UIImage *thumb = [[UIImage alloc]initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:escapedURL]]];
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*100+24, row*80+10, 64, 64);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[view addSubview:button];
if (column == 2) {
column = 0;
row++;
} else {
column++;
}
}
[view setContentSize:CGSizeMake(320, (row+1) * 80 + 10)];
self.view = view;
[view release];
}
- (IBAction)buttonClicked:(id)sender
{
UIImage *boy = [story objectAtIndex:button.tag];
Detailview *detailview=[[Detailview alloc]init];
[detailview initWithItem:boy];
self.detailviewController=detailview;
[self.navigationController pushViewController:self.detailviewController animated:YES];
}
Try this in your buttonClicked:
UIImage *boy = [story objectAtIndex:sender.tag];
You want the tag of sender, not button. button was set to the last one in your list when your buttons were created. sender is the ui object that caused this event.
hi looks like ur using old JSON parser. there is a much better parser for json.
thats JSONKIT.
It has just 2 files(.h and .m) and in just 2 lines of code u can get any data corresponding to the key. u dont hav to iterate through your items array. ur performance rate will definetly incr using JSONKit. if u tryin to use this let me i can post sample codes to parse json contents using jsonkit.
Secondly for the problem u have, u are putting the images in UIScrollview. ur uiscrollview doesnt have navigationcontrol to be pushed to the next view. either remove the scroll view and push from the rootviewcontroller or add navigationcontroller to uiscrollview. guess thats the prob. try it.
all the best.

load animationImage from a table view Controller

I use a UITableViewController to display a list of items, and one of the items selection must lead to a
photo gallery created with animationImages. I usually declare the controllers associated to
the first level selection with something like :
MyController *myController = [[MyController alloc] initWithStyle:UITableViewStylePlain];
myController.title = #"title 1";
myController.rowImage = [UIImage imageNamed:#"myControllerIcon.png"];
..
But I believe a UIViewController is needed to use animationImages..
How can I display a image animation directly from a table view ?
If you have you image sequence build in this manner:
NSArray *myImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"myImage1.png"],
[UIImage imageNamed:#"myImage2.png"],
[UIImage imageNamed:#"myImage3.png"],
[UIImage imageNamed:#"myImage4.gif"],
nil];
UIImageView *myAnimatedView = [UIImageView alloc];
[myAnimatedView initWithFrame:[self bounds]];
myAnimatedView.animationImages = myImages;
myAnimatedView.animationDuration = 0.25; // seconds
myAnimatedView.animationRepeatCount = 0; // 0 = loops forever
[myAnimatedView startAnimating];
[self addSubview:myAnimatedView];
[myAnimatedView release];
Snatched from here
Then you can build your own cell or add the animationImage to the cell by adding it to either:
[cell setImage:myAnimatedView];
[cell setBackgroundView:myAnimatedView];
[cell setSelectedBackgroundView:myAnimatedView]