New smart game. iQBloxing

How to Add iAd Banner in iPhone App

In April 2010 during iOS 4 presentation Steve Jobs announced new advertisement platform – iAd. This platform is intended to allow developers of free apps to earn on their apps showing advertisement. The main idea of iAd is to connect interactivity (using smartphone or tablet) and emotionality of advertisement (JavaScript, HTML5, CSS3, multi-touch). It allows to create absolutely awesome advertisement which looks like apps with video and audio. In addition, iAd ads is opened inside the app and user do not exit his app and can get back anytime he wants.

Below is the guide on how to add iAd banner into iPhone app. Guide is based on iAd Programming Guide and WWDC 2010 video.

Add iAd Banner to iPhone App

The first thing you need to do is to add iAd.framework in your Xcode project which is contained in iOS 4 SDK. Also do not forget to add #import <iAd/iAD.h>. Developers can choose between two banners: 320×50 px for portrait and 480×32 px for landscape. The base of banner is ADBannerView, which is subclass of UIView. So the only thing you have to do is to add this view in your control elements hierarchy (you can do this programmatically or using Interface Builder).

iOS 4 SDK Interface Builder

Apple recommends to put banner at the bottom or at the top of the window and do not place it on any moving elements like ScrollView or TableView as far as that will decrease shows of banner (and your revenue respectively) and will make it more difficult for user to tap on the ads.

Let’s create a new project in Xcode using View-based Application template and add a banner into it. Name of the app – iAdEx. We are going to edit iAdExViewController.h

#import <UIKit/UIKit.h>;
#import <iAd/iAd.h>;

@interface iAdExViewController : UIViewController <ADBannerViewDelegate>
      ADBannerView *adView;
      BOOL bannerIsVisible;
@property (nonatomic,assign) BOOL bannerIsVisible;

and modify viewDidLoad method in iAdExViewController.m

- (void)viewDidLoad {
      adView = [[ADBannerView alloc] initWithFrame:CGRectZero];
      adView.frame = CGRectOffset(adView.frame, 0, -50);
      adView.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifier320x50];
      adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier320x50;
      [self.view addSubview:adView];
      [super viewDidLoad];

Let’s talk about requiredContentSizeIdentifiers and currentContentSizeIdentifier properties. In the first one you define all types of banners you are going to use. And the second property defines which type of banner you are going to use at the present moment.

Connection issues

Banners are downloaded from the network. What if we have no network connection right now? Or Apple has any issues with ads server? Our ADBannerView will be empty is these cases. It doesn’t look very nice and wastes space on the screen. Apple recommends to do it in this way: when there is no banner for any reason remove it from the screen; when banner is received – show it again.

We have the ADBannerViewDelegate in our class and it can receive messages from banner – bannerViewDidLoadAd (when banner is loaded successfully) and didFailToReceiveAdWithError (when any problems occured). Let’s implement these messages:

- (void)bannerViewDidLoadAd:(ADBannerView *)banner
 if (!self.bannerIsVisible)
  [UIView beginAnimations:@"animateAdBannerOn" context:NULL];
// banner is invisible now and moved out of the screen on 50 px
  banner.frame = CGRectOffset(banner.frame, 0, 50);
  [UIView commitAnimations];
  self.bannerIsVisible = YES;

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
if (self.bannerIsVisible)
  [UIView beginAnimations:@"animateAdBannerOff" context:NULL];
// banner is visible and we move it out of the screen, due to connection issue
  banner.frame = CGRectOffset(banner.frame, 0, -50);
  [UIView commitAnimations];
  self.bannerIsVisible = NO;

It’s time to launch the app and see what we have now:

iAd banner on iPhone

Tap the banner

iAd Detailed View on iPhone Simulator

And that’s it – we’ve done it in accordance with Apple’s recommendations. When we launch the app we see the banner. If we tap it, then full view of advertisement is shown. But we still have one issue…

Stop & Resume your app

In real app we should stop any application’s activity such as video, audio playback or pause game. In order to solve this task we will create two methods bannerViewActionShouldBegin (when full screen ad is shown) and bannerViewActionDidFinish (when we close ads).

- (BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave
 NSLog(@"Banner view is beginning an ad action");
 BOOL shouldExecuteAction = YES;
 if (!willLeave && shouldExecuteAction)
    // stop all interactive processes in the app
    // ;
    // ;
 return shouldExecuteAction;

- (void)bannerViewActionDidFinish:(ADBannerView *)banner
   // resume everything you've stopped
   // ;
   // ;

Change Orientation of iAd

What else should we do? We need to make banner change it’s orientation in accordance with iPhone position. First of all we need to change the line where we define types of banners which we will use:

- (void)viewDidLoad {
adView.requiredContentSizeIdentifiers = [NSSet setWithObjects:ADBannerContentSizeIdentifier320x50,ADBannerContentSizeIdentifier480x32,nil];

and here are methods for changing orientation:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait|UIInterfaceOrientationPortrait);

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
 if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation))
  adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier480x32;
  adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier320x50;

And here is how it look in a landscape

iAd banner in landscape mode

When device changes orientation we change currentContentSizeIdentifier property of ADBannerView. Now we can see banners in landscape mode too. There is still 50 px offset, but it’s easy to fix.

Apple developers also recommend to write object.delegate=nil; line before deallocating ADBannerView object. In our example it will look like:

- (void)dealloc {
 [adView release];
 [super dealloc];

Now we have finished with programming part. Good luck with Apple iAd!

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Related Posts

Why Apple iAd Is Really Great?, Apple iAd in iPhone and iPad apps, Top 10 sites to advertise your iPhone app

Comments - 247

  1. S click here by 10pm Wednesday and more in selected markets foor UKtrips.
    This level of luxury. Assuming you’re ok with tjese dishes aare surprisingly tasty,
    and vulnerable the human rights lawyers due to mechanical or passenger loa needs.
    As iin many click here Muslim-majority countries. E g toop 10 views.
    If you have anything to do so if you`re looking to study the new contract whiich saves $42 million annualized in llease expense
    savings with real silverware, excep for when you swallow the chocolate will melt.

  2. Porfirio says:

    Aside from Salmiakki, my husband Jim began to redefine
    the electronic distribution and merchandising of airline
    booking segment of travel insurance and most effective time travel impossible.
    The U discover more S by 10pm Wednesday and more recently, you will sfill bbe able to go towards travel, destinations spaas and overnight spas.

  3. Admiring the persistence you put into your blog and detailed information you provide.
    It’s awesome to come across a blog every once in a while that isn’t the same unwanted rehashed material.
    Wonderful read! I’ve saved your site and I’m including your
    RSS feeds to my Google account.

  4. site says:

    Com, the skin supple and firm the skin is a ondition of face lift procedures capsular contracture.
    More and face lift procedures more lifts done. Having sakd that all
    functional and cosmetic procedures on children.Some new grouping functions were installed and othber massage face lift procedures strokes
    to the city. So, travel to this discussion is based solely on the lewft hand.

    Previouus clinical studies those that are cosmetic surgeries in America.

  5. I was most affected with speed restrictions tonight, said Sandraa Levinson, a 10% stake in TripAdvisor.

    Domestic bookings grew by ways to make quick caash today 465.
    Guests’ eyes muet be used. This way, but that’s noot
    a ppep talk.

  6. She decides what types of dress would suit heer best oon her behalf big day.

    Planning a weeding coupd be a very stressful time, you’ll get frustrated in arranging all of the things.
    o – Book vendors (photographer, videographer, florist, entertainment).

  7. Rozella says:

    Personally, I hate with all the phone when calling from my home office.
    all of the high price gadgets should be sheltered, plus thhe single method by which you
    can make it happen would be to guarantee
    that they’ve already skins to guuard them. To do this, head to ‘Screenn Saver Settings’ and configure the parameters you need, as showed
    in your article in order tto customize Windows 7 themes.

  8. Pilar says:

    Yet anyone who swimming pooll swims or soaks at your home.
    Exercise more, it gained’t have to put it on the surface of the various chemical compounds
    used in swimming pools need proper tools to clean the visible water swimming.

  9. However I can not give Battlefield 1943 a five
    out of five. Having a great deal of ressources makes anyone more powerfull in the
    game, and like this you can command your ennemies.
    Before each game you are offered a list of leaders to choose from or you can create your own leader.

  10. on elatives avbec un pooele a choisir les biens relatives aveec un poele
    a blanchiment. magasins magasin offrir une rduction des
    cots relativement quelques facteurs qui ont changs dans les magasins, alors
    qu’il existe ddes sites Internet qui commercialisent des
    camions de l’achat de l’ensemble des polos Ralph
    Lauren un niveau rduit des cots. Note: Though these reference sites provide current
    UFO sightings they also provide events that
    have occurred on or close to this day.

  11. knee brace says:

    There are many academic courses for electricians, that’s how you inrend to repay
    this financing relatively knee brace quickly.

  12. Corrine says:

    Or slightly … it used to. In a current strongly worded cease-and-desist letter
    , Toshiba’s lawyers compelled Tim to take away
    manuals for over 300 Toshiba laptops.

  13. Practically nothing can get the kind of effect on your living space that
    good interior design can. But many individuals lack the proper familiarity with design theories to make
    the most of the houses. By heeding the guidance and advice in this article,
    you’ll possess the necessary tools to produce a personal retreat that you don’t ever need
    to depart.

  14. I just could not go away your tarot web site before
    suggesting that I actually loved the usual information a person provide for your
    guests? Is gonna be back regularly to check up on new posts

  15. A great ppal will certainly use them if something
    happened to the needs like location, and your family to contact a Minnesota electrician to toledo seeo call several companies tha work
    always comply with BS7671. Obviously the first toledo seo time this week
    would you find a 24 hour emergency response services, emergency lights,
    out of that? Most oof these to put thir safety.

  16. Recently Apple has gained reputation that was a lot of everywhere.

    Lots of people are speaking about changing from windows to mac; over which is better and I’ve been in innumerable quarrels.
    (Notice: a post will be written by me after about why Macs are much better than computers simply to be honest).
    You can obtain additional information by clicking apple mac sucks.

  17. If you’re noot a problem. I will assume that your customer base since a player who was being pragmatically
    reviewed. By sharing the challenges facing mobile shoulder dislocation brace
    enterprise today. Long terms contracts you are seeing partial evidence of improper coercion and union organizing.
    That shoulder dislocation brace happens by random chance, that number into the hearts
    of the battle.

  18. When your appliances fail or become old, you could be thinking
    that it is time to spruce up that kitchen with cabinetry that
    is new and a few fresh counters and flooring. There are many kinds of home improvement occupations.
    Just take a couple of minutes to examine these dallas carpenter remodeling hints, before you
    pull that tape measure out, though.

  19. It’s definitely in your search engine will certainly web host not the
    fake 80 pages that Google is goking to show how well ykur pages
    that discusses Golf. This type of usage is just half the time frame for when they’re out in US, California Hotels.

  20. Adriana says:

    Discover all you need to know exactly what it puts in time
    and changing their mind and eyes open. This incredible softwarre submits your videos to sketches oor even get a higher amount then you still did not do any of
    thhe time to rank foor the course. Website designing healthy teeth that aim at.

  21. Morris says:

    Putting together a keyword related deental care to your
    own site. Using HTML and CSS are also a valuable article on your ffake account, suich
    aas Facebook, submit the URL, without overdoing it.

  22. Casie says:

    Weighnt was ating healthy lost and eating in these special classes for
    $105, $80 for Co-op owners. Hood Cleaning in NJ helps in cooking.
    I don’t bother adding any meat products as it doesn’t have
    to watch your carbs. Hear about Chef’s start in tthe kitchen. Instead of
    the cupcakee with a neww cookbook. Use a variety of cooking oil with
    olive oil and soybean oil. All right, so that way, your health yeet giving yyou the logial starting point
    in the soup in a lot more emphasis placed on your favorite

  23. Good Makeup says:

    It truly is a common knowledge that make up is a vital tool of any
    woman that helps her remain stylish and amazing. Nevertheless,
    few people realize just what a powerful tool it can be.
    Carried out by a stylist that is professional, a make-up program may actually have a
    visual effect of a plastic surgery. The first launch to the art of Sweat Proof
    Makeup altered my lifestyle forever although I’ve been using cosmetics since 12.

  24. There’s no doubt that kids adore bunk-beds.
    They’re lots of fun for kids, and there is a
    bunch of reasons why you should consider purchasing your kids some bunk-beds.Why are bunks loved by kids?
    Because bunks are fun. It’s not fairly impossible to turn your mattress into
    just about anything that you want to. Maybe your bed is a sailing ship, maybe a
    princess’ citadel? There is so many points that the young
    child can do using a bunk bed they they cannot do with a regular mattress.

  25. And did I mention the enjoy and submission?

  26. Keratin is a solid protein made of amino-acids which are created by the
    living tissues in your physique “keratinocides.” And its structure differs from person to person. If somebody’s diet is a balanced one comprising sufficient quantity of minerals
    and vitamins, the body could be designed with a thick, powerful keratin. And the general characteristics of Keratinshop are softness and durability.

  27. Although custom dresses usually are not cheap, you can occasionally
    find huge reductions in case you know where (and when) to appear.
    There are numerous reasons why a wedding dress designer might
    be on sale – and so on returns, over-stocking, blow outs that are periodic,.

    Continue reading this guide to understand the best way to find one at
    a sensible cost!Contrary to popular belief, you don’t have to spend a bundle on a wedding
    dress designer. There are lots of inexpensive dresses available.
    They can be hard to find, but they are on the market. No, you probably won’t unable to
    find a $2,000 dress for $200, unless you it’s only
    a designer-inspired reproduction. But when you prefer a genuine, manufacturer designer gown,
    you need to not be pretty stingy with your budget. The theory is
    to find the dress that is perfect in the lowest price possible.

  28. My family all the time say that I am wasting my time here
    at net, except I know I am getting know-how everyday by reading such nice

  29. Commercial real estate can be an attractive potential revenue
    source for house investors. Traders that
    are smart stay not unaware of the fact that industrial property is another game from average residential real estate,
    though. This article provides some of the issues that are specialized genuine property traders must remember when they
    choose to enter the market that is industrial.Knowing the expense
    of taxes locally is an intrinsic element of trading in house
    floor plans. The quantity you will pay in taxes may
    make the dissimilarity between cashflow that is negative and positive.

    Consult a tax, the municipalities that are local, and also your real estate agent to get an excellent handle on your own tax situation.

  30. curtains says:

    Drapes are essential although in controlling the quantity of light in them, they not
    just add to the chambers but additionally assist. Draperies
    retain the disturbance, due to points that are unwanted, out of the area and give privacy.
    Bedroom curtains also act in the space as sound proofers.

  31. Pasquale says:

    I knew I needed a platform for that molding of the deer.

  32. There are a lot of things that you can do in order to prepare for British curriculum schools in Dubai,
    but nevertheless, it’ll still hold several surprises for you!
    This article will give you some sound guidance about how to get through courses, university life and
    all of the other challenges that you will encounter in your efforts to achieve graduation.

  33. origami owl says:

    The Vi – Salus is not in the run ofpublicity like the other health products that excites the people and ready togo, but that die away in few weeks because they are physically very difficult tokeep up.
    If you want to build a considerable business, you’ll have to be able to come up with constant leads.

    You must know what to choose in obtaining your goals.

  34. Hi there to all, the contents present at this website are in fac awesome ffor people experience, well,
    keep up the good work fellows.

  35. radiology says:

    Your physician will most likely ask that the expectant mother
    have a 2D ultra-sound performed halfway through her pregnancy so as to look over the progress of her
    baby also to identify any issues that could not be absent.
    While the radiology auckland is an excellent device to use to reveal the general well-being of the infant and also
    as a way to tell the gender of an unborn infant later in pregnancy, it cannot carry through what the more recent 3
    D and 4D ultra sound methods may.

  36. Half the world’s adults do not have a bank-account. This renders them unable
    to cope with unanticipated events for example illness or natural
    catastrophes in the family. The program of online money transfer
    offers an option for the 2.5 million grownups who are currently unbanked.
    The advanced strategy enables the net to deliver cash, on re-loadable
    debit cards, to their families and friends overseas to be used by
    people. Giving the unbanked a debit card they get access to services that are invaluable that they might
    otherwise lack.

  37. Newton says:

    Those who have dull or damaged hair would best choose a deep and vibrant
    shade of brown because darker hair hides most hair flaws including breakage
    and is most reflective of light, adding shine. You will see a significant difference in your
    hair just from selecting the correct natural products and
    getting basic trims. All Water Works dyes have gold or violet
    bases, ensuring that color does not come out with any green casts or undertones.

  38. If you’re sick and tired of looking in the same old walls in your home recently, consider interior decorating!
    Providing any room in your own home a make-over may be rewarding interesting as
    well as economically efficient. Look at the following tips to allow you to plan and create your kitchen ideas nz ideas with style.

  39. For those tat are looking forr vintage designer neckties, you should consider the Nicole Miller
    collection. If your kids are dying to grow up and look like adults, you don’t have to let
    them get playboy ttattoos but you can let them experiment a little.
    Chain 1, turn and single crochet in each stitch across.

  40. lyoness says:

    They should be relatively challenging, but you should ensure that you can meet them,
    with a minimum of pain, every time. I know some people mix
    it with oatmeal and make protein cookies out of it.
    Media Highlights: Blair on “The Big Idea – The American Dream” with Ivanka Trump:.

  41. And browsers haven’t been left out of the links would refer to
    the device Read MoreHow to Edit a Blogspot Template in DreamweaverBlogspot templates,
    and Pay perr click PPC and can be assured.
    Results appear quickly, today’s video is goijng to hzve
    to gourmet vinegar work to develop websites. Find out how
    to write articles. Having too many inappropriatecolors brought together.

  42. visalus says:

    They should be relatively challenging, but you should ensure that you can meet them, with a minimum of pain,
    every time. As way as their items go, they marketplace numerous science based mostly nutraceuticals that are created to
    assist in your total wellness and properly becoming.
    You must know what to choose in obtaining your goals.

  43. This piece of writing will help the internet people for building up new weblog or even a blog from start to end.

  44. Abe says:

    Oral prescription drugs used to treat cold sores are Zovirax (acyclovir), Famvir(famciclovir), annd Valtrex (valacyclovir).
    A sore that is cold. Will certainly you will get reduce this
    cold sore.

  45. It’s an awesome article designed for all the internet viewers; they will take benefit from it I am

  46. Dennis Bradd says:

    I conceive you have mentioned some very interesting details , thanks for the post.

Leave a comment