Create your own Xcode code snippets

Using the Code Snippet Library from Xcode is very handy sometimes. However, the library consists only of a small amount of available code snippets. But you are not limited to them, rather than you can create your own code snippets for code patterns you are using very often.

Just follow these easy steps below to create your own snippet.

  1. Write your code snippet down at the code editor and select it.
  2. Be sure to open the code snippet library view within Xcode.
  3. Simply drag the selected code to the code snippet library.
  4. Enter a title and a short description of your snippet.
  5. Enter a shortcut for your snippet. You can choose any combination of letters but you should use something meaningful and you can remember easily.
  6. Choose a platform and the corresponding language the code snippet should be available in.
  7. The completion scope is also very handy to determine in which scopes (methods, class implementations, initializers, …) your code snippet should be available.
  8. The last step is to enter some placeholders within your code snippet. These placeholders will be shown as blue bubbles within your editor when using the code snippet and you can easily navigate to them by using your tab key. To create a placeholder just enter <#your_placeholder_name#>.

 

Example 1: Creating a new UIViewController instance from a xib file and push it to the current navigation controller.

  <#controller#> *controller = [[<#controller#> alloc] initWithNibName:@"<#controller#>" bundle:[NSBundle mainBundle]];
  [self.navigationController pushViewController:controller animated:YES];
  [controller release];

 

Example 2: Creating a new UIBarButtonItem and adding it to the current navigation item.

  UIBarButtonItem *<#button#> = [[UIBarButtonItem alloc] initWithTitle:<#title#> style:UIBarButtonItemStylePlain target:self action:@selector(<#method#>)];
  self.navigationItem.<#left_or_right#>BarButtonItem = <#button#>;
  [<#button#> release];

 

Cheers,

anka

Swipe gestures on UITableView

User interactions on table cells don’t have to be necessarily restricted to simply scroll and tap them. However, with some additional code and the support of gesture recognizers introduced in iOS 3.2 you can give your users the possibility to swipe on your table view cells for exciting additional actions. A common task for that would be to implement a swipe gesture for removing a single item within your table view (seen on several task management and todo apps) or simply changing the state of an item.

All you need is some pretty forward code like the following, which basically creates two gesture recognizers to handle left and right swipes on your table. As you can see we add these gesture recognizers directly to a UITableView rather than to single UITableViewCells.

- (void)viewDidLoad
{
    [super viewDidLoad];
 
    self.title = @"Your controller title";
 
    //Add a left swipe gesture recognizer
    UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self 
                                                                                  action:@selector(handleSwipeLeft:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [self.tableView addGestureRecognizer:recognizer];
    [recognizer release];    
 
    //Add a right swipe gesture recognizer
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self 
                                                        action:@selector(handleSwipeRight:)];
    recognizer.delegate = self;
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [self.tableView addGestureRecognizer:recognizer];
    [recognizer release];    
}

 

The called methods of the gesture recognizers look like as stated below. From the gesture recognizer you’ll get the point of the start of the swipe gesture and with the indexPathForRowAtPoint: method you can get the correct index path for the UITableViewCell the swipe was performed on. From this point on it is up to you to perform more functionality to your table view cell.

- (void)handleSwipeLeft:(UISwipeGestureRecognizer *)gestureRecognizer
{
    //Get location of the swipe
    CGPoint location = [gestureRecognizer locationInView:self.tableView];
 
    //Get the corresponding index path within the table view
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
 
    //Check if index path is valid
    if(indexPath)
    {
        //Get the cell out of the table view
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
 
        //Update the cell or model 
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
}
 
- (void)handleSwipeRight:(UISwipeGestureRecognizer *)gestureRecognizer
{
    //same code for getting UITableViewCell like before
}

 

Hope that helped somebody out there :)

Cheers,
anka

Objective C – HMAC-MD5

Sometimes it is necessary to implement some cryptographic functions for security reasons within your iOS apps. In one of our projects I was faced with the problem of implementing some kind of a two-step registration/confirmation process with a iOS app and a corresponding server-side interface. We decided to implement this by using a generated confirmation code based on HMAC and MD5. Since there is no native support of the iOS framework to realize this, I needed to implement it on my own.

Due to this post Implementing HMAC encryption algorithm in iPhone application it was quite easy to implement a simple category for NSString to provide this functionality. The following code creates a HMAC+MD5 encrypted string based on a given secret and returns it in a hexadecimal string representation.

#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
 
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
 
@implementation NSString (HMAC)
 
- (NSString*) HMACWithSecret:(NSString*) secret
{
    CCHmacContext    ctx;
    const char       *key = [secret UTF8String];
    const char       *str = [self UTF8String];
    unsigned char    mac[CC_MD5_DIGEST_LENGTH];
    char             hexmac[2 * CC_MD5_DIGEST_LENGTH + 1];
    char             *p;
 
    CCHmacInit( &amp;ctx, kCCHmacAlgMD5, key, strlen( key ));
    CCHmacUpdate( &amp;ctx, str, strlen(str) );
    CCHmacFinal( &amp;ctx, mac );
 
    p = hexmac;
    for (int i = 0; i &lt; CC_MD5_DIGEST_LENGTH; i++ ) {
        snprintf( p, 3, "%02x", mac[ i ] );
        p += 2;
    }
 
    return [NSString stringWithUTF8String:hexmac];
}
 
@end

You can now simply use this like the following:

    NSString *strToEncrypt  = @"mytexttoencyrpt";
    NSString *secret        = @"SECRET";
    NSString *hexHmac       = [strToEncrypt HMACWithSecret:secret];
 
    NSLog(@"HMAC in hex is %@", hexHmac);
 
    //Outputs: HMAC in hex is 3849b37cf06d014a13839a9062b5723d

Find the source code for the NSString category at HMAC category.

Cheers,
anka

PostgreSQL trivia

Sometimes it is necessary to use the psql command line tool to quickly explore odds in database. Often you also need to use some commands to view structure of your database or tables. In PostgreSQL (and also in other database systems) you can do that by querying system tables like pg_tables, pg_class, pg_attribute and so on.

Following you’ll find some quick commands for doing that a little bit easier.

 

CommandDescription
\dThis command is in general the shortcut for “describe”. In other database systems the “desc” keyword is used instead.
\dtDisplays all your user defined tables.
\dTDisplays all your user defined data types.
\dfDisplays all your user defined functions.
\diDisplays all your user defined indexes.
\dvDisplays all your user defined views.
\dnDisplays all namespaces.
\duDisplays all users.
\lDisplays all databases.
\d [tablename]Describes the table [tablename] with all fields and indexes.

Also most of this commands can be used in combination with a search pattern. So \dt proj_* will list all tables with the prefix proj_ respectively.

Cheers,
anka

Rails 3, Ruby 1.9.2 and Postgresql on Ubuntu Server without RVM

Recently I faced the task of staging a production environment for a smaller scale installation on a hosted Ubuntu Server.

The box came with Ubuntu Server 10.4 on it and my task was to get the following environment up and running

1) Ruby 1.9.2
2) Rails 3.0.0
3) Postgresql 8.4

Usually in order to complete these steps I would have taken the RVM approach but due to some limitation this wasn’t working at all, so for anyone in the same “situation” I will outline which problems occurred and how I solved them.

Problem 1: perl warnings / general locale problems

apt-get install language-pack-en-base

export LANGUAGE=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
locale-gen en_US.UTF-8
dpkg-reconfigure locales

with the according locales you need for your system. For that thanks goes to Hone Watson

Problem 2: Ruby 1.9.2 without RVM

After that the first thing I wanted to do was to get a running version of Ruby. As RVM was not a working option and the packages are heavily outdated I followed the steps from Eric Peters

Be sure you have no ruby or rubygems from any package installed


sudo apt-get install gcc g++ build-essential libssl-dev libreadline5-dev zlib1g-dev linux-headers-generic libsqlite3-dev libxslt-dev libxml2-dev imagemagick libmysqlclient-dev libmagick9-dev git-core wkhtmltopdf

followed by unpacking and installing

sudo wget ftp://ftp.ruby-lang.org//pub/ruby/1.9/ruby-1.9.2-p0.tar.gz
tar -xvzf ruby-1.9.2-p0.tar.gz
cd ruby-1.9.2-p0/
sudo ./configure --prefix=/usr/local/ruby && sudo make && sudo make install

then you have to adapt your environment in my case i did

sudo vim /etc/environment

and added /usr/local/ruby/bin to the end so it looked like this

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/ruby/bin"

then load the edited environment by doing

source /etc/environment

Now you are almost there :) just add the right symlinks with

sudo ln -s /usr/local/ruby/bin/ruby /usr/local/bin/ruby

sudo ln -s /usr/local/ruby/bin/gem /usr/bin/gem

and check if you have the right gem and ruby with

ruby --version
gem --version

In most cases you also want the latest rubygems so do


sudo gem update --system --> This should give you 1.8.8

Problem 3: Postgresql not starting after install /etc/init.d/postgresql-8.4 status / start etc. gives you no output

In my case installing postgresql just didn’t start the server. Manually starting it didn’t work as well and status or start didn’t produce any output. I searched the web for hours for this one, sometimes purging it and reinstalling seemed to work but I couldn’t consistently reproduce this, although it worked one time for me. So finally I found this bug linked by this blog and it worked.

Do


sudo pg_createcluster 8.4 main

after that you should be able to start the server with


sudo /etc/init.d/postgresql-8.4 start

and it should be up and running.

HTH

J.

Custom background color of UIDatePicker and UIPickerView

Sometimes it is necessary to adjust the color of the standard UIDatePicker and UIPickerView controls within your iOS application. Sadly the iOS SDK doesn’t support to change the background color or even the tint of these controls. A simple workaround for this is to create separate images and use them within an UIImageView as your custom overlay. For this solution I made some simple photoshop templates which you’ll find over here. These photoshop templates are already made for the iPhone retina display and you can scale them down by your own.

Below you’ll find an example with a custom black-grey-based overlay for the UIDatePicker and UIPickerView. Hope this is helpful for somebody.

Cheers,
anka

Take a screenshot within iOS simulator

Whether you want to tweak your user interface or you want to take some promotional images of your iOS application, it is often really helpful to take a screenshot of your iOS application which is running on the iOS simulator. It isn’t a big deal to take a screenshot of a specific region in Mac OS X, simply use  the shortcut Command + Shift + 4. However, an easier way exists by opening your application in the iOS simulator, open the Edit menu, press Ctrl and magically the menu entry Copy Screen shows up. By selecting Copy Screen the current screen in the iOS simulator will be copied to your clipboard and you can insert it in your favorite image editing software.

 




UPDATE:

All problems are solved with the new iOS 5.0 SDK and its corresponding iOS simulator because you have now the option to save the screenshot instantly to your desktop.

Cheers,

anka

Custom Checkmark Gesture Recognizer within iOS

Although there is already an example implementation of a custom checkmark gesture recognizer within the iOS Developer Library (I found it too late), I would like to provide a full example over here again. The objective is very simple: recognize a checkmark gesture within your iOS app on a given view to trigger some kind of event. All we need for that is just a custom gesture recognizer implementation which is able to recognize a checkmark. Further we will define how the gesture should look like so it is a valid checkmark. I used following simple constraints for that:

  • The checkmark has a given start point.
  • The checkmark has two strokes.
  • Each x position of a point within the first stroke is greater than the x position of the previous point (= stroke goes to the right).
  • Each y position of a point within the first stroke is greater than the y position of the previous point (= stroke goes down).
  • If a y position of a point is less than the y position of the previous point then we mark this point as the turn point and we will observe the second stroke (although I am talking about two strokes, they aren’t two independent touches and moves on the device rather than it should be seen as a single move).
  • Each x position of a point within the second stroke is greater than the x position of the previous point (= stroke goes to the right).
  • Each y position of a point within the first stroke is less than the y position of the previous point (= stroke goes up).
  • The second stroke has to be at least 2-times in length as the first stroke.

No we just need to realize these rules within a gesture recognizer implementation. I created a new subclass of UIGestureRecognizer (IMPORTANT: you have to import <UIKit/UIGestureRecognizerSubclass.h> instead of <UIKit/UIGestureRecognizer.h> so you can access and set the state of the gesture recognizer) and named it CheckmarkGestureRecognizer. Within this class it is necessary to override following methods:

- (void)reset;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

Also I added following class members and a custom enumeration:

typedef enum {
    CheckmarkFirstStrokeDown,
    CheckmarkSecondStrokeUp
} CheckmarkGestureState;
CheckmarkGestureState _checkmarkState;
CGPoint _turnPoint;
CGPoint _startPoint;

All gesture recognizers within the iOS SDK are based on an internal state of the type UIGestureRecognizerState. This state tells the gesture recognizer if it is trying to recognize a continues or discrete gesture and if the recognition was successful or did fail. Initially the state is set to UIGestureRecognizerStatePossible and if you try to recognize a discrete gesture (a gesture within a single touch/move) it shouldn’t change until the gesture is finished. As soon as the implementation did recognize the gesture the state will be set to UIGestureRecognizerStateRecognized and a corresponding delegate method will be called automatically. The source code of the mentioned methods above is given over here:

// Override the reset method. This methods gets
// called whenever the state changes to
// UIGestureRecognizerStateFailed.
- (void)reset
{
    [super reset];
    [self resetCheckmark];
}
 
// Touch began on view so save the start point
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
 
    if ([touches count] != 1) {
        self.state = UIGestureRecognizerStateFailed;
        return;
    }
    else
    {
        _startPoint = [[touches anyObject] locationInView:self.view];
    }
}
 
// Track the move of the current gesture
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
 
    if (self.state == UIGestureRecognizerStateFailed)
        return;
 
    // Get the current and previous touch locations
    CGPoint newPoint    = [[touches anyObject] locationInView:self.view];
    CGPoint prevPoint   = [[touches anyObject] previousLocationInView:self.view];
 
    // If we track the first stroke
    if (_checkmarkState == CheckmarkFirstStrokeDown)
    {
        // While we move to the right and downwards
        if (newPoint.x &gt;= prevPoint.x &amp;&amp; newPoint.y &gt;= prevPoint.y)
        {
            // Keep the possible turn point of the stroke
            _turnPoint = newPoint;
        }
        // Else if we change direction to the right and upwards
        else if (newPoint.x &gt;= prevPoint.x &amp;&amp; newPoint.y &lt;= prevPoint.y)
        {
            // Set the state to observe the second stroke
            _checkmarkState = CheckmarkSecondStrokeUp;
        }
        else
        {
            // In any other case the gesture will fail
            self.state = UIGestureRecognizerStateFailed;
        }
    }// Else we track the second stroke
    else if(_checkmarkState == CheckmarkSecondStrokeUp)
    {
        if(newPoint.x &lt; prevPoint.x)             self.state = UIGestureRecognizerStateFailed;     } } // Track the end of the gesture - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {     [super touchesEnded:touches withEvent:event];          if ((self.state == UIGestureRecognizerStatePossible) &amp;&amp; _checkmarkState == CheckmarkSecondStrokeUp)     {         // Get length of both strokes         CGPoint endPoint = [[touches anyObject] locationInView:self.view];         float lengthFirstStroke     = _turnPoint.y - _startPoint.y;         float lengthSecondStroke    = _turnPoint.y - endPoint.y;                  // Checkmark gesture is valid if the second stroke has at         // least 2-times the length of the first stroke         if(lengthSecondStroke &gt; lengthFirstStroke * 2.0)
        {
            // Set state to UIGestureRecognizerStateRecognized and
            // the gesture recognizer will call the defined action
            self.state = UIGestureRecognizerStateRecognized;
        }
        else
        {
            self.state = UIGestureRecognizerStateFailed;
        }
    }
}
 
// The gesture will fail if touche was cancelled
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesCancelled:touches withEvent:event];
    self.state = UIGestureRecognizerStateFailed;
}

That’s all! Create a new instance of CheckmarkGestureRecognizer, set the target and action method and add it to a view. I did this for a example iPad application (you can check out the code at GitHub) and here you can watch the result.

Cheers, anka

AdMob Integration

AdMob

Integration of Google™ AdMob® isn’t a big deal at all. AdMob provides a very good documentation how you can use their SDK within your iPhone/iPad app.

Today I wanna shortly summarize the few important steps you need to do to integrate AdMob:

  • First of all sign up at AdMob.
  • After that, add a new site/app within AdMob and provide the basic information requested.
  • Download the iPhone/iPad AdMob SDK and import it to your iPhone/iPad Xcode project.
  • Add following frameworks to your target:
    • libz.1.2.3.dylib
    • MediaPlayer.framework
    • MessageUI.framework
    • QuartzCore.framework
  • Now let your application delegate implement the AdMobDelegate protocol and add a adMobVisible boolean variable.
  • Within your application delegate add following methods for creating, showing and hiding your AdMob banner:
    // Add a new AdMob banner view to the current view
    - (void) addAdmobView
    {
       // Create a new AdMobView for iPhone portrait mode
       // At this point you can check your device and environment and
       // provide the correct sized ad banner.
       AdMobView *adMobView = [AdMobView requestAdOfSize:ADMOB_SIZE_320x48 withDelegate:self];
     
       // Set position to the top but hide it
       CGRect frame   = adMobView.frame;
       frame.origin   = CGPointMake(0, -adMobView.frame.size.height);
       adMobView.frame = frame;
     
       // Add Banner to current view
       [viewController.view addSubview:adMobView];
       adMobVisible = NO;
    }
     
    // Hide the given AdMob banner with animation
    - (void) hideAdMobView:(AdMobView*)adView
    {
       @synchronized(self)
       {
          if (adMobVisible == YES)
          {
             [UIView beginAnimations:@"animateBannerOff" context:NULL];
             // Assumes the banner view is placed at the top of the screen.
             adView.frame = CGRectOffset(adView.frame, 0, -adView.frame.size.height);
             [UIView commitAnimations];
     
             // Update view status
             adMobVisible = NO;
          }
       }
    }
     
    // Show the given AdMob banner with animation
    - (void) showAdMobView:(AdMobView*)adView
    {
       @synchronized(self)
       {
          if (adMobVisible == NO)
          {
             [UIView beginAnimations:@"animateBannerOn" context:NULL];
             // Assumes the banner view is just off the top of the screen.
             adView.frame = CGRectOffset(adView.frame, 0, adView.frame.size.height);
             [UIView commitAnimations];
     
             // Update view status
             adMobVisible = YES;
          }
       }
    }
  • Now call the method addAdmobView at the end of your application:didFinishLaunchingWithOptions method and a new ad banner will be created and added to the top of your current view.
  • Further more you need to implement some delegate methods:
    // Return your AdMob app publisher id
    - (NSString *)publisherIdForAd:(AdMobView *)adView
    {
      // If you are going to develop a universal app
      // you can return different publisher id depending
      // on the current device over here. This makes reporting
      // easier.
       return @"YOUR_ADMOB_PUBLISHER_ID";
    }
     
    // Return the top level view controller of your ad view
    - (UIViewController *)currentViewControllerForAd:(AdMobView *)adView
    {
       return viewController;
    }
     
    // Show the view when a new ad arrived
    - (void)didReceiveAd:(AdMobView *)adView
    {
       [self showAdMobView:adView];
    }
     
    // Show the view when the ad was refreshed
    - (void)didReceiveRefreshedAd:(AdMobView *)adView;
    {
       [self showAdMobView:adView];
    }
     
    // Hide the view in case of not receiving an ad
    - (void)didFailToReceiveAd:(AdMobView *)adView;
    {
       [self hideAdMobView:adView];
    }
     
    // Hide the view in case of not receiving an refreshed ad
    - (void)didFailToReceiveRefreshedAd:(AdMobView *)adView;
    {
       [self hideAdMobView:adView];
    }
  • For testing purpose you should also implement the testDevices delegate method to return an array of UDIDs of your test devices. This will ensure, that you don’t get real ads on your test devices or within the simulator (clicking on real ads will be seen as a violation against AdMob terms & conditions).
    // Return an array of UDIDs of your test devices
    - (NSArray *)testDevices
    {
       // Only return the UDID of the iphone simulator
       return [NSArray arrayWithObjects:ADMOB_SIMULATOR_ID, nil];
    }
  • Start the application within your simulator and you will see an ad banner at the top of your app and it will receive some test ads.

As you can see it isn’t that hard to use the AdMob SDK within your app. Go ahead and try it on your own. You can also check out my example at my GitHub repository. If you want to try out the example you need to download and import the AdMob SDK on your own.

Cheers,
anka

iAd Integration

iAd

Advertisements are another option to provide your iOS applications still for free but also to get some cash back for your work. Although ads are not that popular to app users Apple made a big hit with their new iAd network. I’d like to call iAd the next level of advertisement on mobile devices because they offer a totally different experience compared to common text or banner based ads.

First steps to enable iAd are:

  1. Go to iTunes Connect and fill out all necessary information on the iAd Network contract (It will take some time until Apple confirms your contract).
  2. Setup your application information at iTunes Connect as usual.
  3. Go to the iAd network settings of your application and enable the iAd network and choose your primary target group.

After that go straight to your Xcode project and check out following things:

  1. View your project info and add a weak (iOS < 4.0 doesn’t support iAd) reference to the iAd framework.
  2. Go to your application delegate interface and make it implement the ADBannerViewDelegate protocol.
  3. Add a simple variable to observe the iAd visibility BOOL iAdVisible.
  4. Go to your application delegate implementation and setup your iAd banner view. To check if iAd is available on the current run-time environment I implemented a simple category for the UIDevice class.
    - (void) setupiAd
    {
    	if([UIDevice isIAdAvailable] == NO)
    		return;
     
    	// Initialize a new iAd banner view
    	ADBannerView *adView = [[ADBannerView alloc] initWithFrame:CGRectZero];
     
    	// Set the delegate and hide the view initially
    	adView.delegate		= self;
    	adView.hidden		= YES;
     
    	// Different iOS versions support different view sizes
    	// but we just wanna add a portrait ad view
    	if(&amp;ADBannerContentSizeIdentifierPortrait != nil)
    		// Size identifier for IPAD + IPHONE
    		adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
    	else
    		// Size identifier only for IPHONE
    		adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier320x50;
     
    	// Move the banner view to the background (across the screen top)
    	adView.frame	= CGRectOffset(adView.frame, 0, -adView.frame.size.height);
    	adView.hidden	= NO;
     
    	// Add the banner to the current view
    	[viewController.view addSubview:adView];
    	[adView release];
     
    	// Set status of iAd banner
    	iAdVisible = NO;
    }
  5. Now you are almost done. Call setupiAd within your applicationDidFinishLaunching: method and this will add an iAd banner view to your current view if iAd is available. The last step is to implement the ADBannerViewDelegate methods and to simply show the banner view whenever ad content is available and hide the banner view when no ad content is available or some kind of error occurred. It is very important to hide the banner once an error occurred and to show the banner if content is given. The iAd framework will stop providing you with ad content if you don’t act properly.Some helper methods to hide/show banner view:
    - (void) hideBannerView:(ADBannerView*)banner
    {
    	if (!iAdVisible)
    		return;
     
    	[UIView beginAnimations:@"animateAdBannerHide" context:NULL];
     
    	// Assumes the banner view is placed at the top of the screen.
    	banner.frame = CGRectOffset(banner.frame, 0, -banner.frame.size.height);
    	[UIView commitAnimations];
     
    	// Update visibility state
    	iAdVisible = NO;
    }
     
    - (void) showBannerView:(ADBannerView*)banner
    {
    	if (iAdVisible)
    		return;
     
    	[UIView beginAnimations:@"animateAdBannerShow" context:NULL];
     
    	// Assumes the banner view is just across the top of the screen.
    	banner.frame = CGRectOffset(banner.frame, 0, banner.frame.size.height);
    	[UIView commitAnimations];
     
    	// Update visibility state
    	iAdVisible = YES;
    }

    Implementation of the ADBannerViewDelegate methods:

    - (void)bannerViewDidLoadAd:(ADBannerView *)banner
    {
    	// Ad content available -&gt; show banner
    	[self showBannerView:banner];
    }
     
    - (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
    {
    	// In any error case hide the banner
    	[self hideBannerView:banner];
     
    	NSLog(@"ADBannerView didFailToReceiveAdWithError: %d, %@, %@",
    		  [error code],
    		  [error domain],
    		  [error localizedDescription]);
    }
     
    - (BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave
    {
    	// Save your application state here
    	return YES;
    }
     
    - (void)bannerViewActionDidFinish:(ADBannerView *)banner
    {
    	// Restore your application state here
    }

That’s it! Start your application with your simulator and you should see an empty view with an iAd banner view and some test content in it:


If you watch the simulator awhile you will notice that sometimes the banner view disappears and your debugger console will show up a message like ADBannerView didFailToReceiveAdWithError: 3, ADErrorDomain, The operation couldn’t be completed. Ad inventory unavailable. This error messages are intended by Apple so you can test whether your implementation works correctly or not.

To get the full example source code you can check out my iAdIntegration project on GitHub.

Cheers,
anka