2011年11月29日星期二

Amazing Apple-like Documentation

Amazing Apple-like Documentation:

I know I know, Documentation is a bad bad word, especially for us creative people. The true creativity is in writing code, not in writing comments, isn’t it?

Well, regardless, you might find yourself in the situation that you want other people to reuse your code. Or better yet, a different self of you in a year should be able to understand your line of reasoning of today. If you do programming for a longer time you will pass the phase of being shocked at how bad your code was and then get into the phase of having no idea what you where thinking. So a liberal sprinkling of comments can help you get up to speed on your old code.


I invented a technique of chewing on a portion of a programming puzzle where you comment almost every line of code as if you were to explain to somebody the steps in your ingenious approach. Maybe somebody else coined a term for this, for me it helps me sort my thoughts. And probably will do the same a year or ten from now. So commenting comes naturally to me, Documentation by Comment-ation is a logical extension to the concept.

Readability

Apple has nicely written documentation for their APIs though their process of creating it is hard to duplicate for us solo or small team developers. Apple has an entire department that writes the documentation the “Apple Developer Publications Department”, googling for them you can even find a two-year-old style guide for writers. Just consider this quote from it on page 6 just to see how much over our heads this “proper documenting” is:

“In general, follow the style and usage rules in:

  • The American Heritage Dictionary
  • The Chicago Manual of Style
  • Words into Type

Exceptions to certain guidelines in these resources are noted in this guide.

In cases where reference sources conflict with each other, follow:

  • The Chicago Manual of Style for questions of style and usage
  • The American Heritage Dictionary for questions of spelling

Also refer to any department-specific materials provided by your editor.”

No way I’m going to start perusing a dictionary for my comments! And I guess neither will you…

Apple apparently is using the RenderX XEP engine to convert their own XML documentation to the nice PDF and HTML output you see online today. That’s the second reason why their process is out of reach for us.

Enter AppleDoc

One-person company Gentle Bytes saw our need for a simple and usable way to generate nice-to-look-at documentation from source code comments. So he started the AppleDoc open-source project in or around April 2009. It’s grown over 2 years and in January 2011 the version got bumped to 2.0. This is finally a full rewrite that no longer depends on Doxygen to parse the source code.

AppleDoc works such that it parses your source code and assembles the source comments in a structure strikingly similar to what we are used to from Apple. There is documentation as to how to construct your comments but I found it not very intuitive. So let me give you an overview and tutorial here as to what I learned to help you get up to speed as quickly as possible on using AppleDoc yourself.

Setup

You need to clone the AppleDoc Xcode project from github and build the command line tool. I assume that you have previously set up github on your development machine.

git clone git://github.com/tomaz/appledoc.git
cd appledoc
open appledoc.xcodeproj

In Xcode switch to the appledoc target and build it. You will see the appledoc entry in the Products group turn black.


Copy the appledoc command line utility to any folder in your path, I put it in /usr/local/bin. This way it is available regardless of what your current working directory is. To see that this is working and to see the appledoc help you can do “appledoc –help”.

Commenting Correctly

AppleDoc requires that you adhere to a certain style of commenting that is slightly different from the standard C comments you are used to, namely /* comment */ and // single line.

Classes and Categories

For every class or category that you are documenting, add one or more paragraphs of comments describing what the class is used for. This goes between the imports and the interface in the header file.

/** This class demonstrates AppleDoc.

A second paragraph comes after an empty line.

int i=0;
i++;

And some sample code can also be in a block, but indented with a TAB.
*/

Note the second asterisk on the opening of the comment. Paragraphs are separated by an empty line. All this text is parsed as markdown syntax, the inventor Gruber has an introduction. You can have sample code in the text as well, in it’s own block and indented with a tabulator. The above turns into a nicely formatted Overview section.

AppleDoc automatically turns anything looking like an Objective-C method into a cross-reference. That’s usually what we want, but will get you some warnings if you reference external classes in a sample block. See below how you can solve that.

Methods

The comment block before a method (again in header) will be turned into the description 0f the method. The default behavior is to use the first paragraph for the short description and all paragraphs for the “Discussion”. I disabled this repeating of the first paragraph because I find that it looks weird to have the same text twice, not like Apple.


/**---------------------------------------------------------------------------------------
* @name A name under which this method appears under "Tasks"
*  ---------------------------------------------------------------------------------------
*/

/** This is the first super-awesome method.

You can also add lists, but have to keep an empty line between these blocks.

- One
- Two
- Three

@param string A parameter that is passed in.
@return Whatever it returns.
*/
- (NSString *)someMethodWithString:(NSString *)string;

The comment block with the @name serves for the grouping of methods in the “Tasks” section at the beginning of the page for the class/category. You should group similar methods under one such section, you don’t have to repeat it because the @name is good until the next one. You see that you can also have lists (numbered or not). You need an @param for each parameter of the method. If it has a non-void return value then you also need an @return to describe that. Omitting any of these will get you a warning.


You see that the first paragraph of the description ended up at the top, the rest of it including the list went to the Discussion part.

Some more bells and whistles are possible, shown here:


/** This is the second super-awesome method.

Note that there are additional cool things here, like [direct hyperlinks](http://www.cocoanetics.com)

@param number A parameter that is passed in, almost as cool as someMethodWithString:
@return Whatever it returns.
@see someMethodWithString:
@warning *Warning:* A blue background.
@bug *Bug:* A yellow background.
*/
- (NSString *)someMethodWithInteger:(NSInteger)number;

This shows cross references inline and via the @see tag. For external hyperlinks you put the link words in square brackets, the link itself in round ones. Finally you have a choice of blue or yellow box for warnings/notices.


Unfortunately there is no support for constants, enums and other things you might want to put in your headers, but it’s being worked on as we speak. For now you should probably put the possible values for an typedef’d enum in a simple list.

Building the Docset and HTML

Once you have added sufficient commentary as outline above you will want to build the documentation. AppleDoc primarily builds docsets which are essentially bundles with a bunch of HTML and xml index files. These docsets integrate with your Xcode for easy browsing and searching.

It took me quite a bit of tweaking until I got the parameters right to get the output I wanted. Also there are apparently some bugs that manifest themselves if you have some switches in the wrong oder. For quick building I set up a Documentation target where I added a “Run Script” build phase to execute this script. This would just as well work in a separate shell script, though you’d have to substitute the actual path for the PROJECT_DIR.


/usr/local/bin/appledoc \
--project-name "DTFoundation" \
--project-company "Cocoanetics" \
--company-id "com.cocoanetics" \
--docset-atom-filename "DTFoundation.atom" \
--docset-feed-url "http://cocoanetics.github.com/DTFoundation/%DOCSETATOMFILENAME" \
--docset-package-url "http://cocoanetics.github.com/DTFoundation/%DOCSETPACKAGEFILENAME" \
--docset-fallback-url "http://cocoanetics.github.com/DTFoundation/" \
--output "~/help" \
--publish-docset \
--logformat xcode \
--keep-undocumented-objects \
--keep-undocumented-members \
--keep-intermediate-files \
--no-repeat-first-par \
--no-warn-invalid-crossref \
--ignore "*.m" \
--ignore "LoadableCategory.h" \
--index-desc "${PROJECT_DIR}/readme.markdown" \
"${PROJECT_DIR}"

Here are my reasons for the various switches:

  • project-name, project-company and company_id are standard
  • the atom filename and the urls are necessary to let the docset know where it can get an update
  • the output directory should be a place outside of your Xcode project. I found that having the generated documentation inside a github project does not make sense.
  • publish-docset causes AppleDoc to generate the Atom feed and xar archive file
  • logformat-xcode makes the output compatible with Xcode so that you get inline warnings
  • keep-intermediate-files is necessary to preserve the original HTML output which you can put on your server for online reading
  • no-repeate-first-par is the setting that does not duplicate the first paragraph into the discussion section
  • no-warn-invalid-crossref omits the annoying warnings that you get when AppleDoc cannot find a reference to class or method
  • we’re ignoring the .m files because otherwise AppleDoc would also try to get comments from these. We only want the comments from headers used also we don’t want the documentation say that a method was defined in the .h and the .m files which is unlike Apple.
  • the LoadableCategory.h is another file we explicitly need to ignore, it is a dummy class that forces the linker to also load certain tagged categories. No use having that in the documentation.
  • the index-desc is the path to a markdown file which additionally gets injected into the index page

The last switch is of special interest. Without it the index page of the docset is relatively barren. But since all of AppleDoc is based on markdown you can also re-purpose the readme file you usually have in the project root of your project as an introduction to the project. Write once, reuse: I’m loving it!

Publishing

AppleDoc will also install a generated docset into the same location where Apple’s docsets are residing. You can see these and install new ones via Xcode preferences, Downloads, Documentation tab.

You can add docsets on this screen via the plus button and by specifying the URL of the Atom feed. Remember, AppleDoc can generate this feed for you. If you leave the generated output in the publish folder around and update the project version then AppleDoc will add the new version to the feed file. So all you need is to copy the xar and the atom files to your web server after making sure that you specified the URLs correctly. This way somebody only needs to have the URL of the atom feed to install the docset.

The contents of the html folder in your output directory contain a full HTML site for the entire documentation. You can upload that to your web site as well, it is essentially the same content as in the docset. If you do, then people can browse the documentation outside of Xcode and you can also specify the URL there as fallback URL in your docset.

GitHub has a mechanism called GitHub Pages which you can enable via the admin area of every project. Once enabled you can put the web server files into a gh-pages branch of your open-source project. I finally got it working as well, but it is a bit weird having to constantly move around between the master and the gh-pages branch.

Conclusion

By adopting the described style of commenting methods and classes/categories you immediately reap the benefit of being able to generate beautiful docsets and HTML documentation. You can also inject your additional markdown files to enhance the index or even going as far as adding custom images and full HTML files. Development on AppleDoc continues – although slowly – and we’re looking forward to getting support for other things we’d like to document: notifications, protocols, enums and constants.

The main advantage of AppleDoc is that the comments also enhance your source code, so that even people without Xcode can read what you wrote. This way other developers benefit because they can look up your methods and see what your thoughts where. Often the availability of documentation is what many people use to decide whether or not they should add a dependency on your library or framework.

Finally it is yourself who will benefit in the long run because your commentary will allow you to understand what you where thinking many years ago. Don’t discount this possibility, we all get older all the time.

2011年11月24日星期四

How to Integrate AdWhirl into a Cocos2D Game

How to Integrate AdWhirl into a Cocos2D Game:
This is a blog post by iOS Tutorial Team member Ibrahim Kteish, a student inspired by the iPhone with a passion for creating iOS software, and the cofounder of istockplus.com.

Learn how to get a high fill rate with ads in your game with AdWhirl!
Learn how to get a high fill rate with ads in your game with AdWhirl!

If you want to make an ad-based game, your first thought might be “well, I’ll just enable iAd!” Although iAd is a great ad network (and definitely easy to integrate, since it’s built into iOS), if you try it out in practice you’ll notice very low fill rates.

This means that often when you want to display an ad, there won’t be an ad available, and so you’ll get less money than you potentially might have otherwise. And since the goal is to make money, obviously this isn’t ideal!

This is where an ad mediation framework like AdWhirl comes to the rescue – and that’s the focus of this tutorial!

AdWhirl is a free, open source tool that allows developers to serve ads from any number of Ad networks you have accounts on, as well as your own house ads (to run your own ad campaigns and cross-promote your apps), via one simple client SDK.

By utilizing multiple ad networks and Switch ad networks on the fly, you can select which ones perform best for your app and ensure you have a high fill rate. Note AdWhirl won’t “mediate” your payments, the payments will be made by each network you’ve signed on.

In this tutorial, we will show you step-by-step how to get started with AdWhirl, and integrate it into one of the Cocos2D tutorials from this site. If you follow along, you’ll be all set up with AdWhirl and ready to integrate it into your own apps or games!



AdWhirl: An Overview


The way AdWhirl works is you configure a number of ad networks which you want to serve ads, and AdWhirl chooses one to serve an ad for you, based on your preferences and ad availability.

To configure AdWhirl to use an ad network, you have to create an account on that network. You also have to integrate that ad network’s SDK into your project.

AdWhirl supports a huge array of ad networks (currently 17 at the time of writing this article!), and we could set up AdWhirl to use all 17 networks, but then this tutorial would take forever!

So for the purposes of this tutorial, we are just going to configure AdWhirl to use two ad networks:

  • iAd. iAd is Apple’s built-in advertising solution. You might have read about it already in our How To Integrate iAd into your iPhone App tutorial. iAd is great, but its fill rate is often low. So when it’s not available, AdWhirl can help with that by serving ads from another provider such as AdMob.
  • AdMob. AdMob is one of the world’s largest mobile advertising platforms and claims to serve more than 40 billion mobile banner and text ads per month across mobile Web sites and handset applications. Their rates are generally not as high as iAd, but they have more ads available.

Before we do anything with AdWhirl, we need to enable iAds for our app, and set up an AdMob account. So let’s get started!

Enabling iAds for your App


In order to receive iAds in your app, you need to enable the iAd service for your app in iTunes Connect via the following steps:

  1. Log onto the iOS Developer Center, go to the iOS Provisioning Portal, and create a new App ID for your app. We’re going to be integrating AdWhirl into a space game in this tutorial, so you might want to name it something like “com.yourdomain.spacegame.”
  2. Log onto iTunes Connect and create a new app, choosing the App ID you just created. Just enter placeholder information for now until you get to the “waiting for upload” stage. Don’t worry you can change all this info later, we just have to create an enter to make iTunes Connect happy for now.
  3. Once you’ve created your app’s entry, open it up in iTunes Connect and click “Set Up iAd Network”, as shown below:

Set Up iAd Network Button in iTunes Connect

  1. Finally you must specify whether your audience is under 17 years of age, as shown in the following screenshot. This helps target your ads more appropriately for your age group.

Selecting age group for ads in iTunes Connect

Click the Enable iAds button and Save. The only other thing you have to do is go to the Contracts & Banking module in iTunes Connect, and accept the iAd network agreement if you haven’t already.

Creating an AdMob Account


Next, we will create an account for the AdMob network. Go ahead and visit the admob.com and click on Get Started:

Get Started button in AdMob

Second, follow the steps to create an account by filling in the info and accepting the terms of service. When you’re done you should see a page like this:

Account created for AdMob

Next, we need to create a new app in order to get a Publisher ID that we need for AdWhirl.

To do this, click on the Sites & Apps tab, and select the Add Site/App button from the dropdown. It will prompt you to enter your payment details, as you can see in the screenshot below:

Entering payment details in AdMob

Once you’ve entered your payment details, choose iPhone app from the next page:

Choosing app type in AdMob

A dropdown will appear to allow you to enter some additional information on your app. Enter the information as shown below, and then click continue:

Entering app details in AdMob

You will then arrive at a screen where you can download the AdMob SDK. Be sure to download this, because you’ll need the SDK later on in this tutorial.

Now we just need to get the Publisher ID for the new app we created. To do this, click the “Go to Sites/Apps” button, scroll down to your new Space Game entry, move your mouse over it so the “Manage Settings” button appears, and click that button.

Manage Settings for an AdMob app

Finally, you will see your Publisher ID toward the top of this information sheet! Copy this down, as you will need it later in this tutorial.

Getting AdMob Publisher ID

Creating an AdWhirl Account


It’s easy to get started with AdWhirl. Simply visit adwhirl.com and click the “Sign Up Now” button:

Click the sign up now button

You’re then presented with a sign up page. Simply fill in the text fields with your data, enter the captcha, and select the checkbox, as shown below:

Signing up to AdWhirl

Once you’ve clicked register you will get a message saying to check your email as shown in the next screenshot:

Receiving confirmation message

Go ahead and find the email sent to you, click the link, and you will get a confirmation message as shown below:

After verifying email

Click log in, and fill in the dialog boxes to log into your new account. You’ll arrive at a page where you can add and track your applications:

Main AdWhirl page

Congrats, you now have an AdWhirl account! Let’s go ahead and an app next.

Adding an App


From the Apps tab, you can see all of the apps that you’ve integrated with AdWhirl.

Click the Add Application button to add a new app, as shown in the next screenshot:

Adding a new app in AdWhirl

You’ll then be presented with the following page:

Add a new App page in Adwhirl

Enter the name and App Store URL of your app (if your app isn’t released yet, you can leave the URL field blank), and choose iPhone for the Platform field.

Optionally, you can set additional preferences of how ads should display in this app:

  • Refresh Rate: determines how many seconds before a new ad appears.
  • Transition Animation: describes how to execute an animation from the old state to the new state over time.
  • Allow Location Access: if this is on, will ask allow AdWhirl to attempt to get location data for the user. The problem is this will cause a popup to the user asking if it’s OK for the app to get their location, and if the app doesn’t need it this will be suspicious and annoying to the user.

For this tutorial, let’s leave all of those options at the default settings. Click Add App, and your app will be created in the AdWhirl system (you might have to refresh the page):

AddWhirl app created

Click on the app name that you just created, and you’ll see the app’s SDK key listed to the right of its name:

AdWhirl SDK key

This key is quite important – you’ll be pasting this into the SDK code to identify your app to AdWhirl’s servers.

Configuring Ad Networks


The next step is to configure the parameters for each ad network that you want to serve ads to your app. In this tutorial, we’re just going to configure the AdMob and iAd accounts we set up, but you can enable more ad networks if you want in your own apps!

Let’s start by setting up AdMob. Find the AdMob entry, click the Configure button next to it, and you’ll be prompted to enter your AdMob publisher ID. Enter the Publisher ID you get from earlier in the tutorial:

Configuring AdMob for AdWhirl

Next find the iAd entry, click the Configure button next to it, and you’ll be prompted to enter your Apple ID. Enter your Apple ID to continue:

AdWhirl iAd

Once you’ve done this, you can turn the network on or off using the On-Off button, and choose the percent of traffic that you want to assign to each network as the next screenshot shown (AdMob On iAd Off).

Ad OnOff

The way this works is AdWhirl chooses an ad network based on the traffic allocation percentages you’ve applied. When it’s time to serve an add, these allocation percentages tell AdWhirl where to send ad requests on the first attempt. If an ad request fails, AdWhirl will try another network according to the backfill priorities you set (which we’ll configure in a minute), one after another until an ad is found or the list is exhausted.

Note that even if a network has a 0% allocation, it may still get some requests through backfill. To ensure that no ad requests ever go to a network, make sure to switch it off using the On-Off button.

iAd and AdMob ON

Note that your allocation percentages must add up to 100% before you’ll be able to save these settings as next screenshot shown.

iAd and AaMob allocation

As always when you are done with Ad Network Settings, click on Save changes.

Last but not least, go to Backfill priority as shown in the screenshot below – you’ll use this page to tell AdWhirl what priorities to follow in case an initial ad request is unfilled by one of your networks. AdWhirl uses low numbers to represent high priority:

Backfill Priority

Creating House Ads


House Ads (formerly known as custom ads) are ads of your own creation that you display in your apps. You can use these to cross-promote your other apps, apps of your friends, or anything else you might want to use them for.

To create a House Ad in your AdWhirl account, click the House Ads tab along the top of the screen App as shown in the next screenshot.

Adding a house ad

Click the “Add House Ad” button and the next screenshot appears:

Creating a house ad

Fill in the information as you desire. After creating your ad, be sure to go back to your Ad Network Settings screen, turn on House Ads, and edit the traffic percentages and backfill priority as you would like.

Integrating the AdWhirl SDK


At this point, you should have the AdMob SDK (if you don’t, you can get it by clicking “Get Publisher Code” from your Space Game app settings in AdMob, or download it here).

But you haven’t downloaded the AdWhirl SDK yet, so go ahead and download it now. Obviously choose the iPhone SDK, as shown below:

Downloading the AdWhirl SDK

We’re going to integrate AdWhirl into one of the tutorials from this site – specifically the game from the Space Shooter tutorial. If you purchased the Space Game Starter Kit you will be particularly happy we chose this game to base it on, since it will be really easy apply this tutorial to the Starter Kit! :]

So go ahead and download the space game from the tutorial. Unzip and run it in Xcode and make sure everything is working properly. Note that this game requires the accelerometer, so you might want to try it on your device if you want to play.

Next, go ahead and unzip the AdWhirl SDK. Once you unzip the file, drag only the AdWhirl subfolder into the group in your project. Verify that “Copy items into destination group’s folder (if needed)” is checked, and click Add as shown in the next screenshot.

Adding the AdWhirl folder to your project

Once you’ve added the AdWhirl folder to your project Add the following frameworks as shown in the next screenshot:

  • AddressBook.framework
  • CoreLocation.framework
  • MapKit.framework (weak-linked for OS 2.X support)
  • MediaPlayer.framework
  • MessageUI.framework (weak-linked for OS 2.X support)
  • SystemConfiguration.framework
  • iAd.framework (required for iAd, weak-linked for OS 3.X support)
  • libsqlite3.dylib
  • libz.dylib

Adding the frameworks required by AdWhirl to your project

The final step is to remove the adapters in AdWhirl/adapters that we don’t need. Open that folder and remove all of the files except for the ones we need (iAd, AdMobs, and AdNetworkAdapter), as shown below:

AdWhirl Files

Now that we have the AdWhirl SDK brought into your project, let’s bring in the AdMob SDK. Unzip the file, and drag the GoogleAdMobAdsSDK folder into the space game project. Make sure “Copy items into destination group’s folder (if needed)” is selected, and click Finish, as shown in the next screenshot:

Drag AdMob SDK

Compile and run your project on your device to make sure everything works so far, and finally let’s start coding!

Using the AdWhirl SDK

Open HelloWorldLayer.h and make the following modifications:


// Add to top of file
#import "AdWhirlView.h"
#import "AdWhirlDelegateProtocol.h"
#import "AppDelegate.h"
#import "RootViewController.h"

enum GameStatePP {
kGameStatePlaying,
kGameStatePaused
};

// Mark class as implementing AdWhirlDelegate
@interface HelloWorldLayer : CCLayer <AdWhirlDelegate>

// Add inside @interface
RootViewController *viewController;
AdWhirlView *adWhirlView;

enum GameStatePP _state;

// Add after @interface
@property(nonatomic,retain) AdWhirlView *adWhirlView;
@property(nonatomic) enum GameStatePP state;


Here we import the header files we need for AdWhirl, and the AppDelegate and RootViewController (since we’ll be adding a view to the view controller to display the ad view).

Then we create an enumeration called GameStatePP to keep track of the two different game states we’re going to have – playing or paused.

We also mark the class as implementing AdWhirlDelegate, and create some instance variables and properties.

Next, switch to HelloWorldLayer.m and make the following modifications:


// Add after @implementation
@synthesize state = _state, adWhirlView;

// Add at end of init
self.state = kGameStatePlaying;

// Add in dealloc
self.adWhirlView.delegate = nil;
self.adWhirlView = nil;


This is just the basic setup code to synthesize our properties, initialize the game state, and cleanup in dealloc. Time to move onto the fun stuff!

Implementing AdWhirlDelegate

Now we will implement the Adwirl Delegate methods. Go to the end of HelloWorldLayer.m and the following 2 methods before the @end :


- (void)adWhirlWillPresentFullScreenModal {

if (self.state == kGameStatePlaying) {

[[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];

[[CCDirector sharedDirector] pause];
}
}

- (void)adWhirlDidDismissFullScreenModal {

if (self.state == kGameStatePaused)
return;

else {
self.state = kGameStatePlaying;
[[SimpleAudioEngine sharedEngine] resumeBackgroundMusic];
[[CCDirector sharedDirector] resume];

}
}


The first method is called when an ad is about to presented full-screen. Since we don’t want to mess up the player’s game, we pause the game here while the ad displays. Note we check here to see if the game is already paused before attempting to pause.

The second method is called when the user closes the ad, so it resumes the game if it is paused.

Next, let’s implement the methods to return the adWhirl application key and the view controller AdWhirl will present its ads in. Add the following methods next:


- (NSString *)adWhirlApplicationKey {
return @"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
}

- (UIViewController *)viewControllerForPresentingModalView {
return viewController;   
}


Replace the “xxx” in the adWhirlApplicationKey with the application key you got from AdWhirl (under “SDK Key”).

Next, implement the following methods to respond to receiving an ad and displaying it in the proper orientation:


-(void)adjustAdSize {
//1
[UIView beginAnimations:@"AdResize" context:nil];
[UIView setAnimationDuration:0.2];
//2
CGSize adSize = [adWhirlView actualAdSize];
//3
CGRect newFrame = adWhirlView.frame;
//4
newFrame.size.height = adSize.height;

//5 
CGSize winSize = [CCDirector sharedDirector].winSize;
//6
newFrame.size.width = winSize.width;
//7
newFrame.origin.x = (self.adWhirlView.bounds.size.width - adSize.width)/2;

//8 
newFrame.origin.y = (winSize.height - adSize.height);
//9
adWhirlView.frame = newFrame;
//10
[UIView commitAnimations];
}

- (void)adWhirlDidReceiveAd:(AdWhirlView *)adWhirlVieww {
//1
[adWhirlView rotateToOrientation:UIInterfaceOrientationLandscapeRight];
//2    
[self adjustAdSize];

}


There’s a good amount of code here, so let’s explain it step by step, starting with the adjustAdSize method (which makes the ad appear on the bottom center of the screen):

  1. Here we use the beginAnimations:context: to start animating the ad view. You call this on a UIView before changing one or more of its property values, such as its size, position, or opacity, to make those changes appear animated.
  2. Get the actual size of the Ad and assign it in adSize.
  3. Declare newFrame so we can assign a new size.
  4. Set newFrame height equal to adSize height.
  5. Declare winSize to hold window size parameters.
  6. Set newFrame width to equal window width.
  7. Position newFrame so that it is centered on the screen.
  8. Position newFrame so that it appears on the bottom of the screen.
  9. Set the adWhirlView’s frame to the new position we just calculated.
  10. Calls the commitAnimations class method to end the animation block.

If you want your ad to appear in a different location, you can modify this code.

The adWhirlDidReceiveAd method works as follows:

  1. Because of Space game in on landscape mode, we have to set the interface orientation to that. If your game in Portrait mode just comment the first line of code.
  2. call adjustAdSize() method.

Just two methods left! Add the following 2 methods:


-(void)onEnter {
//1
viewController = [(AppDelegate *)[[UIApplication sharedApplication] delegate] viewController];
//2
self.adWhirlView = [AdWhirlView requestAdWhirlViewWithDelegate:self];
//3
self.adWhirlView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;

//4
[adWhirlView updateAdWhirlConfig];
//5
CGSize adSize = [adWhirlView actualAdSize];
//6
CGSize winSize = [CCDirector sharedDirector].winSize;
//7
self.adWhirlView.frame = CGRectMake((winSize.width/2)-(adSize.width/2),winSize.height-adSize.height,winSize.width,adSize.height);
//8
self.adWhirlView.clipsToBounds = YES;
//9
[viewController.view addSubview:adWhirlView];
//10
[viewController.view bringSubviewToFront:adWhirlView];
//11
[super onEnter];
}

-(void)onExit {
if (adWhirlView) {
[adWhirlView removeFromSuperview];
[adWhirlView replaceBannerViewWith:nil];
[adWhirlView ignoreNewAdRequests];
[adWhirlView setDelegate:nil];
self.adWhirlView = nil;
}
[super onExit];
}


According to Cocos2d CCNode class reference, onEnter is called when you first enter a scene (i.e. when the transition starts), and onExit is called when you exit a scene (i.e. when the transition ends).

In onEnter, the first thing we need to do is get the root view controller. There’s only one catch: the current cocos2d project templates do not assign the new root view controller to the UIWindow’s property, so normally it’s unavailable unless you expose it in the AppDelegate class itself.

So go ahead and open AppDelegate.h and quickly declare a property for it:


@property (nonatomic, retain) RootViewController *viewController;


And switch to AppDelegate.m and synthesize this property:


@synthesize viewController;


Next, let’s return to onEnter and discuss it line by line:

  1. Gets the view for the ad from AdWhirl and sets the layer as its delegate.
  2. Sets the autosizing mask to center the ad.
  3. Retrieves the configuration from adwhirl.com.
  4. Gets the actual size of the Ad and assign it in adSize instance.
  5. Declare winSize to hold window size parameters.
  6. Sets the posion of AdWhirlView to the center bottom.
  7. Makes sure any content is clipped to the ad view’s bounds.
  8. Adds the ad view as a subview of the view controller.
  9. Brings it to the front.
  10. Calls onEnter from the superclass.

The onExit method just does cleanup – if an ad is visible, it removes it from the superview, makes it ignore any further ad requests, and sets the delegate to nil.

Compile and run, and you should see ads now in your game!

Simulator

Where To Go From Here?


Here is an example project with all of the code from the above tutorial.

Integrating Ads in your application not a bad idea and if you know how to market your app well, you will satisfied with the result. Here’s a screenshot for my AdMob account for 1 month for my first game Face N’ Chase. Note this is only from AdMob – and more downloads equates to mo’ money!

my AdMob

Best of luck enabling AdWhirl in your Cocos2D game, and I hope you enjoyed this tutorial! If you have any questions or comments, please join the forum discussion below.



This is a blog post by iOS Tutorial Team member Ibrahim Kteish, a student inspired by the iPhone with a passion for creating iOS software, and the cofounder of istockplus.com.

How to Integrate AdWhirl into a Cocos2D Game is a post from: Ray Wenderlich

2011年11月22日星期二

Working with Date and Time in Cocoa (Part 2)

Working with Date and Time in Cocoa (Part 2):
In part 2 of my little series on date and time handling in Cocoa I am going to talk about date parsing and formatting. In other words: how to convert strings into date objects and vice versa. You should read part 1 first if you haven’t yet to get an overview of the classes used by Cocoa’s date and time system.


NSDateFormatter



When working with date and time, two very common requirements are, (1) displaying dates in your UI, and (2) reading in date/time values from external sources like a web service or text file. Since humans are not very good at interpreting the second-based timestamps that NSDate uses to store dates internally, both of these tasks usually make it necessary to convert between NSDate and NSString or vice versa.


In the Foundation framework, the class to use for this task (in either direction) is NSDateFormatter. Let me show you how it works.


1. Turning Dates Into Strings



Let’s start with the easier (because less error-prone) of the two directions: turn an NSDate instance into a readable string. Usage of the NSDateFormatter class always involves three steps: (1) create the date formatter; (2) configure it; (3) send it a stringFromDate: message to get the result. Obviously, the configuration step is where the interesting stuff happens. We should differentiate between two separate use cases: do we want to create a human-readable output or do we need to create a string according to a specific format to be read by another API?


Formatting for Humans: Let the User Decide



When displaying dates in your app’s UI, you should always take the user’s preferences into account. Fortunately, that is easy with NSDateFormatter. To simply convert an NSDate into an NSString use code like this:


NSDate *myDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
NSString *myDateString = [dateFormatter stringFromDate:myDate];
NSLog(@"%@", myDateString);


With my current locale settings (German), the output looks like this: 22.11.2011 18:33:19, but that’s just me. By default, NSDateFormatter observes the current user’s locale settings so other users might see results like Nov 22, 2011 6:33:19 PM or 2011-11-22 下午6:33:19 or even २२-११-२०११ ६:३३:१९ अपराह्, all for the same input and with the same code.


As a developer, you are not supposed to care about the actual output. Just use the setDateStyle: and setTimeStyle: methods to control how short or long the output should be. Possible values are NSDateFormatterShortStyle, NSDateFormatterMediumStyle, NSDateFormatterLongStyle and NSDateFormatterFullStyle; you can also use NSDateFormatterNoStyle to suppress the date or the time component in the resulting string.


The class method +localizedStringFromDate:dateStyle:timeStyle: provides a shorter way to achieve the same result as the code snippet above.


If you want to have more control over the output format, you can set a specific format using the setDateFormat: method. Note, though, that Apple specifically discourages that approach for human-readable dates since there is no date and time format that is accepted worldwide. NSDateFormatter understands the date format specifiers of the Unicode spec for date formats. If you want to go this route, have a look at the +dateFormatFromTemplate:options:locale: class method. It lets you specify a string of date format specifiers that your output string should include and returns an appropriate date format string for the specified locale.


Formatting for Machines: Controlled Environment Needed



It is a whole other matter if you need to create a date string according to the specification of a certain file format or API. In such a case, you usually have to follow a very strict spec to make sure the other party can read the string you are generating.1


It should be clear that we must use the setDateFormat: method here. But that is not enough. Remember from part 1 that you can represent the same point in time very differently, depending on the calendar and time zone. By default, NSDateFormatter uses the user’s current calendar and time zone, which are possibly different from the requirements. Most file formats and web APIs use the western, Gregorian calendar, so we need to make sure that our date formatter uses it, too:


NSDate *myDate = [NSDate dateWithTimeIntervalSinceReferenceDate:343675999.713839];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[dateFormatter setCalendar:calendar];


We must also make sure to set the date formatter’s locale to a generic value so as not to run into conflict’s with the user’s locale settings, which can influence the naming of weekdays and months as well as the clocks 12/24 hour setting. The date formatter’s setLocale: method expects an instance of the NSLocale class. To create one, we need to specify a locale identifiers. These usually consist of a combination of a language and a country code, such as @"en_US". For our needs, however, there exists the special locale identifier @"en_US_POSIX" that is guaranteed to not change in the future.


Note that a locale also includes a calendar setting so setting the calendar explicitly as we did above is no longer necessary (but does not hurt).


NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:locale];


The date’s time zone can possibly be included in the formatted output string. But as I also mentioned in part 1, time zone identifiers such as “+01:00”, “PST” or “CET” are notoriously ambiguous. In most cases, it’s best to stick with UTC:


NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
[dateFormatter setTimeZone:timeZone];


Now, we are finally ready to set our date format and create the result string. For example, to format a date according to the common RFC 3339 (ISO 8601) standard:


[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
NSString *myDateString = [dateFormatter stringFromDate:myDate];
// => 2011-11-22T17:33:19Z


Again, see the Unicode standard mentioned above for a list of possible format specifiers. Pay special attention to the year format specifier @"yyyy". It is different than the capitalized @YYYY, which represents the year of the date’s week and not the year of the day. 99% of the time, you probably want to use @”yyyy”. I have seen this bug so many times in production code that it’s not funny anymore so make sure your unit tests catch it.2


Also note that I am using the literal character 'Z' to represent the UTC time zone we set on the date formatter before. If you need to include the time zone in your format string, make sure to experiment with the possible time zone format specifiers (z, Z, v, V, each with 1-4 characters) and different time zones to really understand what you’re getting yourself into.3 As I said, dealing with time zones is no fun, especially when it comes to ambiguous abbreviations or daylight savings time. It’s best to avoid if at all possible.


2. Turning Strings Into Dates



Let’s move on to the other side of NSDateFormatter: parsing a string representation of a date and/or time and converting it to an NSDate instance. Your main use case for this should be the parsing of dates you read in from a web service API or a text file.


Parsing Machine-Generated Dates



In this case, you use the class much like in the reverse case that we just discussed:



  1. Create an NSDateFormatter.

  2. Create a controlled environment by setting the formatter’s locale and possibly time zone as specified by the input format. In most cases, this means the en_US_POSIX locale and the UTC time zone.

  3. Set the formatter’s date format string to the specified format.

  4. Call dateFromString:.
For example, here is how to parse a date from an RSS feed entry of the form Mon, 06 Sep 2009 16:45:00 -0900 as specified in RFC 822:


NSString *myDateString = @"Mon, 06 Sep 2009 16:45:00 -0900";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:locale];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];

NSDate *myDate = [dateFormatter dateFromString:myDateString];
NSLog(@"%@", myDate);
// => 2009-09-07 01:45:00 +0000


Note how we did not set the date formatter’s time zone explicitly here. Instead, the Z character in the format string is now a format specifier for the time zone rather than the literal character it was in the example above. Also note that the output format of NSLog() shows date and time in UTC but it really represents the exact same point in time as the input string.


If a date formatter cannot parse the string, dateFromString: returns nil. Your code must be able to deal with this case gracefully.


Parsing Free-Form Date Strings



What if you don’t know the exact format of the string, e.g. because you want to let the user enter a date and time in a free-form text field4? I am afraid that NSDateFormatter will probably not be a big help then. The class does have a setLenient: method that enables heuristics when parsing a string. However, even in lenient mode you are still required to specify an exact date format. In lenient mode, the formatter correctly parses a date string containing slashes (@"03/11/2011 11:03:45") when the date format specifies blanks (@"dd MMM yyyy HH:mm:ss") but that seems approximately to be the extent of what it can do.


For really lenient parsing with NSDateFormatter, you would probably have to try multiple formats and check for success after each attempt. The Unicode standard includes some suggestions for lenient parsing if you want to go that route.


NSDataDetector to the Rescue!



A more promising approach might be the relatively new NSDataDetector class. Although not a classic member of the date and time handling classes in Cocoa, I want to mention it here for its ability to match, among other things, dates and times in free-form strings such as e-mail messages.


Because NSDataDetector is a special kind of regular expression, its API is completely different:


NSString *myDateString = @"24.11.2011 15:00";
NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate error:&error];
NSArray *matches = [detector matchesInString:myDateString options:0 range:NSMakeRange(0, [myDateString length])];
for (NSTextCheckingResult *match in matches) {
   NSLog(@"Detected Date: %@", match.date);           // => 2011-11-24 14:00:00 +0000
   NSLog(@"Detected Time Zone: %@", match.timeZone);  // => (null)
   NSLog(@"Detected Duration: %f", match.duration);   // => 0.000000
}


In this case, the detection worked great5, and the detector can also deal with relative strings such as @"next Monday at 7 pm" or @"tomorrow at noon". NSDataDetector always seems to use the current locale and time zone to interpret dates in strings.


Miscellaneous Findings



Use Thread-Local Storage for NSDateFormatter



The -[NSDateFormatter init] method is quite expensive. If you need the same date formatter repeatedly, you should cache it, either in a static variable as in this example in Apple’s Technical Q&A QA1480 (see Listing 2) or, even better, by using Thread-Local Storage as explained by Alex Curylo in his article Threadsafe Date Formatting.


More Efficient Date Parsing



If you still encounter performance problems with NSDateFormatter, note this suggestion in the same QA1480:



Finally, if you’re willing to look at solutions outside of the Cocoa space, it’s very easy and efficient to parse and generate fixed-format dates using the standard C library functions strptime_l and strftime_l. Be aware that the C library also has the idea of a current locale. To guarantee a fixed date format, you should pass NULL to the loc parameter of these routines. This causes them to use the POSIX locale (also known as the C locale), which is equivalent to Cocoa’s “en_US_POSIX” locale.



For a data point, see Sam Soffes’s article how he improved the performance of his date parsing code by a factor of more than 20× by switching from NSDateFormatter to C-based date parsing.


GMT != UTC



Cédric Luthi discovered a seemingly weird NSDateFormatter behavior last weekend. See the following code:


NSString *dateString = @"0001-01-01 00:00:00 GMT";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
NSDate *myDate = [df dateFromString: dateString];
NSLog(@"%@", myDate);


The result of the log statement: 0001-01-01 01:27:24 +0000. Hm, 01:27:24? Where can such a weird result come from? It turns out the answer is the time zone GMT. Do the same with UTC as the time zone and the result is the expected 0001-01-01 00:00:00 +0000.


So it seems that when dealing with historical dates, UTC and GMT are not identical in Cocoa. Instead, the system seems to use past definitions of GMT that were valid at the date in question. When I investigated this further, I found out that only for dates later than 9 April, 1968, GMT and UTC are identical in Cocoa. So beware of the difference if your app deals with the past. Use UTC as your time zone if you want to interpret all dates in today’s time system.





  1. Wouldn’t it be great if all web services used Unix timestamps to represent dates? I could omit this entire section as the conversion from and to NSDate would be trivial. For some reason, however, most APIs use string-based dates, which at least have the advantage of being human-readable.↩



  2. For example, the year-of-week for 1 January 2005 is 2004 because that date belongs to the last calendar week of 2004 rather than the first calendar week of 2005. Use NSDate *testDate = [NSDate dateWithTimeIntervalSinceReferenceDate:126273600.0] in your unit test and assert that you get the correct result for both format strings @"yyyy" and @"yyyy".↩



  3. By the way, CodeRunner, which I reviewed recently here on the blog is an awesome little app to experiment with date formatters. I used it constantly while writing this article.↩



  4. There are a number of apps that let you do just that, for example iCal in Lion, the great Fantastical app and Google Calendar.↩



  5. My time zone is one hour earlier than UTC, hence the time difference between input and output string.↩



UIView Animation Tutorial: Practical Recipes

UIView Animation Tutorial: Practical Recipes:
Use some UIView Animation Recipes you can use in your apps!
Use some UIView Animation Recipes you can use in your apps!

This is a blog post by iOS Tutorial Team member Fabio Budai, an Objective C developer from Italy.

One lesson I learned the hard way is that graphics and animations are really important in iPhone Apps, and not only in games. Utilities also need a nice UI and some cool graphic effects.

It may be true that most of these animations are useless! At least when it comes to functionality. But being “good-looking” can be the small and winning difference between your app and the competitor’s.

Sometimes your design needs a complex UI that can contain a lot more objects than you can fit on a screen. A good solution to this problem is to display parts of your interface only as needed (stuff like pickers, keyboards, extra buttons…). Again, these items must show up with cool effects to make the app seem polished.

Luckily, UIKit has some really powerful built-in animations, and in iOS 4, blocks make using them really easy.

We already covered how to use UIView Animations in the UIView Animation Tutorial posted here almost a year ago, so you might want to go through that tutorial first.

This tutorial takes things a step further by giving some practical examples and recipes for how you can use UIView Animations in your own apps, to add some polish and spice!



Getting Started


Create a new project in XCode: File\New\New Project. Pick the Single View Application template and call it UIAnimationSamples.

Make sure you check ARC and Storyboard. Even if in this tutorial we won’t be focusing on these new technologies, it is a good practice to keep all your new projects up-to-date. In any case, you can use almost all of the code in this tutorial “as is” in pre-ARC projects.

Create a new file (File\New\New File) and choose the iOS\Cocoa Touch\Objective-C category template. Enter “Animation” for the Category and “UIView” for Category on, and finish creating the file. A category allows us to add some methods to an already existing class (UIView in this case) without subclassing it: a very neat and powerful way to expand an object’s functionality. We’ll put all the animation code this category.

Add the following code inside the interface in UIView+Animation.h:


- (void) moveTo:(CGPoint)destination duration:(float)secs option:(UIViewAnimationOptions)option;


Then add the implementation in UIView+Animation.m as follows:


- (void) moveTo:(CGPoint)destination duration:(float)secs option:(UIViewAnimationOptions)option
{
[UIView animateWithDuration:secs delay:0.0 options:option
animations:^{
self.frame = CGRectMake(destination.x,destination.y, self.frame.size.width, self.frame.size.height);
}
completion:nil];
}


This adds a new method to ALL instances of UIView that moves the view itself from its current position to the new destination in “secs” (seconds; it’s a float, so you have a fine control of duration). The option relates to the animation curve used (more on this later). For now, we’ll use the default value of zero.

How does this work? Our code uses the [UIView animateWithDuration:] API on one of the properties of a UIView that can be animated: the frame. By simply changing it in the block “animations,” you tell Core Animation to move it to the new coordinates, taking “secs” time in doing it, and automatically calculate (and draw) all the intermediate “steps” to get a smooth animation.

It’s as easy as that: you just set the new position and the framework will animate it moving in a straight line to the destination! Let see this in action by adding some code to the view controller.

Replace ViewController.h with the following:


#import <UIKit/UIKit.h>
#import "UIView+Animation.h"

@interface ViewController : UIViewController
@property (nonatomic,weak) IBOutlet UIButton *movingButton;

- (IBAction) btnMoveTo:(id)sender;

@end


This simply declares a button that we’ll make move around the screen, and a method that will start the button moving. We’ll add the GUI for this later.

Then, make the following changes to ViewController.m:


// Add right after @implementation
@synthesize movingButton;

// Add right before @end
#pragma mark - animation actions

- (IBAction) btnMoveTo:(id)sender
{
UIButton* button= (UIButton*)sender;
[movingButton moveTo:
CGPointMake(button.center.x - (movingButton.frame.size.width/2),
button.frame.origin.y - (movingButton.frame.size.height + 5.0))               
duration:1.0 option:0]; // above the tapped button
}


To see the result, we need to execute just one final step: add the controls in the View.

Open up MainStoryboard.storyboard, and change the background color of the View to dark blue. Then drop a Round Rect button anywhere inside the View and set its title to “Here”. Then Control-click on the button, drag from the “Touch Up Inside” action to the View Controller, and connect it to the “btnMoveTo” method. Then make three copies of this button and place them around the View (one easy way to do this is to Option-drag the button).

Finally, add another Round Rect button to the center of the view, and set its type to Custom. Use this arrow as the image, set the width and height to 50 pixels. Control-click the View Controller and drag a line from the movingButton outlet to this new button to connect it.

Your storyboard should now look something like this (but it’s OK if your buttons are in different positions):



Now build and run! The arrow will move above the “Here” button. Pretty cool for just a few lines of code, eh?



This recipe is useful to highlight the user selection (like the small blue triangle in the Twitter app) or to slide in a bigger view (you put just a small part of a view onscreen, and allow the user to slide the rest of the view into the screen by tapping the arrow).

CGAffineTransform


Probably the most powerful animatable property on UIView is transform, which takes a CGAffineTransform. This is a matrix that expresses how each pixel of the UIView should be modified, applying some math formulas.

Don’t worry, you don’t actually have to remember linear algebra, because there are some built-in CGAffineTransforms to make life nice and simple. We’ll focus on two of them:

  • CGAffineTransformScale: Allows you to scale a view up or down, optionally using different factors for the x and y axes. A value of 10.0 means “make the view 10 times bigger than the actual frame.” Please note that applying this transform may invalidate the Frame property.
  • CGAffineTransformRotate: Allows you to rotate a view by a given angle. It uses radians, the standard unit of angular measure. One radian is equal to 180/π degrees.

It is important to understand how animation of transforms works: you can combine multiple transforms of different kinds, but iOS will “see” only the final result. So if you make a 360° (2π radians) rotation, the net effect is no rotation at all, and you won’t see any animation on your view!

Keep in mind that:

  • Rotations up to 180° are animated clockwise
  • Rotations from 180° to 360° are animated counter-clockwise (it takes the shortest path, so 270° is rendered as a -90° rotation)
  • All rotations over a complete circle (360°) are ignored, and a 2π module is applied

This will be easy to see when you try it out – so let’s see rotation in action!

In UIView+Animation.h, add the following inside the @interface:


- (void) downUnder:(float)secs option:(UIViewAnimationOptions)option;


And then add the implementation in UIView+Animation.m:


- (void) downUnder:(float)secs option:(UIViewAnimationOptions)option
{
[UIView animateWithDuration:secs delay:0.0 options:option
animations:^{
self.transform = CGAffineTransformRotate(self.transform, M_PI);
}
completion:nil];
}


This simply animates the view to rotate 180° over the specified number of seconds.

Add a new method that will run this rotation in ViewController.h:


- (IBAction) btnDownUnder:(id)sender;


Then add the implementation in ViewController.m:


- (IBAction) btnDownUnder:(id)sender
{
UIButton* button= (UIButton*)sender;
[button downUnder:1.0 option:0];
}


And finally, open up MainStoryboard.storyboard, control-click the button, and drag a line from the “Touch Up Inside” action to the View Controller and connect it to the btnDownUnder method.

Run the app. Every time you tap the arrow button, you should see it flipping up/down (rotating 180°) with a smooth rotation. And you can still move it around!

This recipe may be useful for something like an on/off switch. You can play with different angles to generate arrows for different directions using just one image.

A scale transformation is perfect for creating a zoom effect that can be great for pickers. And a picker is exactly what we need in the next section!

Animation Curves


If you pay close attention to the animation we just coded, you’ll notice that the arrow starts slow, then speeds up, then slows down again until it stops (you can raise the duration to better see this effect).

What you are seeing is the default “curve” for UIView animations. Curves are actually acceleration curves that describe the speed variations of the animation. There are 4 curves available:

  • UIViewAnimationOptionCurveEaseInOut: start slow, speed up, then slow down
  • UIViewAnimationOptionCurveEaseIn: start slow, speed up, then suddenly stop
  • UIViewAnimationOptionCurveEaseOut: start fast, then slow down until stop
  • UIViewAnimationOptionCurveLinear: constant speed

UIViewAnimationOptionCurveEaseInOut is the default because the effect seems very “natural.” But of course, “natural” depends on what you want to do.

To play with different curves we can simply use the corresponding constant as an “option” parameter. But since we’re still learning what they do, let’s build a “curve picker” to try them all out!

iPhone pickers are somewhat ugly objects that eat lots of space and give a generally poor user experience. A good solution is to create a custom, good-looking picker view that’s shown only when necessary (automatically or when the user tap on a button). We’ll use the scale transform to bring up the picker with a cool zoom animation.

We need some more code to made this work, but please note that most of it is for handling the picker: the animations are still made with just 2-3 lines of code.

First we add the zoom animations in UIView+Animation.m, and this time we’ll animate the adding/removing of a subview:


- (void) addSubviewWithZoomInAnimation:(UIView*)view duration:(float)secs option:(UIViewAnimationOptions)option
{
// first reduce the view to 1/100th of its original dimension
CGAffineTransform trans = CGAffineTransformScale(view.transform, 0.01, 0.01);
view.transform = trans; // do it instantly, no animation
[self addSubview:view];
// now return the view to normal dimension, animating this tranformation
[UIView animateWithDuration:secs delay:0.0 options:option
animations:^{
view.transform = CGAffineTransformScale(view.transform, 100.0, 100.0);
}
completion:nil]; 
}

- (void) removeWithZoomOutAnimation:(float)secs option:(UIViewAnimationOptions)option
{
[UIView animateWithDuration:secs delay:0.0 options:option
animations:^{
self.transform = CGAffineTransformScale(self.transform, 0.01, 0.01);
}
completion:^(BOOL finished) {
[self removeFromSuperview];
}];
}


This is similar to the rotate transform we ran earlier, except it uses a scale transform instead of a rotate transform. It also adds and removes the new subview as appropriate.

Next add the definitions in UIView+Animation.h:


- (void) addSubviewWithZoomInAnimation:(UIView*)view duration:(float)secs option:(UIViewAnimationOptions)option;
- (void) removeWithZoomOutAnimation:(float)secs option:(UIViewAnimationOptions)option;


OK, we’re done with the zoom animation code. Now let’s create the curve picker!

Create a new file with the iOS\Cocoa Touch\Objective-C class template, name the Class AnimationCurvePicker and make it a subclass of UIView. To make it easy to layout, also create a XIB where we can design the view, by creating another file with the iOS\User Interface\View template (name it AnimationCurvePicker.xib).

The code we’ll add to AnimationCurvePicker class is pretty simple: we’ll add a method to loads the xib and set the delegate (that will be the ViewController, of course).

So open up AnimationCurvePicker.h and replace it with the following:


#import <UIKit/UIKit.h>

@interface AnimationCurvePicker : UIView
@property (nonatomic,weak) IBOutlet UITableView *animationlist;

+ (id) newAnimationCurvePicker:(id)pickDelegate;
@end


Then replace AnimationCurvePicker.m with the following:


#import "AnimationCurvePicker.h"

@implementation AnimationCurvePicker
@synthesize animationlist;

+ (id) newAnimationCurvePicker:(id)pickerDelegate
{
UINib *nib = [UINib nibWithNibName:@"AnimationCurvePicker" bundle:nil];
NSArray *nibArray = [nib instantiateWithOwner:self options:nil];
AnimationCurvePicker *me = [nibArray objectAtIndex: 0];
me.animationlist.delegate = pickerDelegate;
me.animationlist.dataSource = pickerDelegate;
return me;
}

@end


Then open up AnimationCurvePicker.xib, change the view class to AnimationCurvePicker, set the status bar to “none” and modify the frame to 280 width and 300 height.

Next, add a table view of the same dimensions, and set the style to grouped. Control-click the view (“Animation Curve Picker”) and drag a line from the animation list outlet to the Table View.

It should look like this:



Finally, you need to make some modifications to ViewController.h. I’ve included the entire file here for easier editing:


#import <UIKit/UIKit.h>
#import "UIView+Animation.h"
#import "AnimationCurvePicker.h"

@interface ViewController : UIViewController {
NSMutableArray *curvesList;
int selectedCurveIndex;
UIView *pickerView;
}

@property (nonatomic,weak) IBOutlet UIButton *movingButton;

- (IBAction) btnMoveTo:(id)sender;
- (IBAction) btnDownUnder:(id)sender;
- (IBAction) btnZoom:(id)sender;

@end


Next, make the following changes to ViewController.m:


/// put this just under @synthesize...
static int curveValues[] = {
UIViewAnimationOptionCurveEaseInOut,
UIViewAnimationOptionCurveEaseIn,
UIViewAnimationOptionCurveEaseOut,
UIViewAnimationOptionCurveLinear };

/// Replace vieDidLoad with the following
- (void)viewDidLoad
{
[super viewDidLoad];
curvesList = [[NSMutableArray alloc] initWithObjects:@"EaseInOut",@"EaseIn",@"EaseOut",@"Linear", nil];
selectedCurveIndex = 0;
}

/// modify previous IBAction methods to pass the curve to animation
- (IBAction) btnMoveTo:(id)sender
{
UIButton* button= (UIButton*)sender;
[movingButton moveTo:
CGPointMake(button.center.x - (movingButton.frame.size.width/2),
button.frame.origin.y - (movingButton.frame.size.height + 5.0))               
duration:1.0
option:curveValues[selectedCurveIndex]]; // above the tapped button
}

- (IBAction) btnDownUnder:(id)sender
{
UIButton* button= (UIButton*)sender;
[button downUnder:1.0 option:curveValues[selectedCurveIndex]];
}

/// Then add the following lines:
- (IBAction) btnZoom:(id)sender
{
UIButton* button= (UIButton*)sender;
pickerView = [AnimationCurvePicker newAnimationCurvePicker:self];
// the animation will start in the middle of the button
pickerView.center = button.center;
[self.view addSubviewWithZoomInAnimation:pickerView duration:1.0 option:curveValues[selectedCurveIndex]];
}

#pragma mark - animation curves picker
// handling the picker, that is a simple tableview in this example
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [curvesList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];

if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text = [curvesList objectAtIndex:indexPath.row];

if (indexPath.row == selectedCurveIndex)
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
cell.accessoryType = UITableViewCellAccessoryNone;

return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return @"Select the Animation Curve to be used";
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
return @"Curves will not affect total duration but instant speed and acceleration";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
if (selectedCurveIndex != indexPath.row)
{
NSIndexPath *oldPath = [NSIndexPath indexPathForRow:selectedCurveIndex inSection:indexPath.section];
cell = [tableView cellForRowAtIndexPath:oldPath];
cell.accessoryType = UITableViewCellAccessoryNone;

selectedCurveIndex = indexPath.row;
}

if (pickerView)
{
[pickerView removeWithZoomOutAnimation:1.0 option:curveValues[selectedCurveIndex]];
pickerView = nil;
}
}


Last step: in MainStoryboard.storyboard, add a button somewhere near the middle of the View, put “Picker” as Text and connect it to “btnZoom:” method of File Owner.

With this code, we create a custom view “AnimationCurvePicker” derived from UIView that contains a tableview, then delegate the ViewController to manage user choices, and we use the selected values to change the Animation Curve used by all the animations we made.

On top of this, we animate the addition of this subview with a zoom animation.

This recipe can be useful if you want to bring up a popup control in your app, and of course the animation curves themselves can be useful for all sorts of effects.

Run the app, and play around with the different animation curves!



Making Your Own Transform


To create really complex gaming-type animations, it’s probably better to use OpenGL or Cocos2D, but don’t underestimate the power of UIKit.

Also keep in mind that another property you can animate is the Alpha Channel. This makes it really easy to create fade effects, which is another nice way to add/remove subview.

Now we’ll add another button to the main View that will bring in a HUD-like view with a fade-in animation. This view will have a “STOP” button that dismisses the animation with a funny “draining the sink” custom effect!

First import this FakeHUD.png image into your project, then add a new Objective C class called FakeHUD, derived from UIView. Why “fake”? Because it only pretends to look like a HUD, when it’s actually just a full screen view… ;)

Let’s code!

Replace FakeHUD.h with the following:


#import <UIKit/UIKit.h>
#import "UIView+Animation.h"

@interface FakeHUD : UIView

- (IBAction)btnStop;
+ (id) newFakeHUD;
@end


Replace FakeHUD.m with the following:


#import "FakeHUD.h"

@implementation FakeHUD
// create a new view from the xib
+ (id) newFakeHUD
{
UINib *nib = [UINib nibWithNibName:@"FakeHUD" bundle:nil];
NSArray *nibArray = [nib instantiateWithOwner:self options:nil];
FakeHUD *me = [nibArray objectAtIndex: 0];
return me;
}

- (IBAction)btnStop
{
// the following method will be defined and explained later: ignore the warning
[self removeWithSinkAnimation:40];
}
@end


Now add a xib named FakeHUD.xib (with the iOS\User Interface\View template) and change the class of the main UIView in FakeHUD. Set the simulated status bar to “none,” and change the background color to “clear.”

Add an UIImageView, set FakeHUDD.png as the image, and again change the backgound color to clear. After that, put a couple of labels in the bigger circle (they pretend to be the messages for the user) and a big white Activity Indicator (check the “Animating” flag).

Put a UIButton (type “custom”) in the smaller circle, with “STOP” as the text, change the text color to white, and connect “the tap up inside” event to the btnStop: IBAction of the FakeHUD view.

With this, the HUD is complete, and should look like this:



Now the “draining the sink” animation, finally!

Add to UIView+Animation.h:


- (void) addSubviewWithFadeAnimation:(UIView*)view duration:(float)secs option:(UIViewAnimationOptions)option;
- (void) removeWithSinkAnimation:(int)steps;
- (void) removeWithSinkAnimationRotateTimer:(NSTimer*) timer;


And the implementation in UIView+Animation.m:


// add with a fade-in effect
- (void) addSubviewWithFadeAnimation:(UIView*)view duration:(float)secs option:(UIViewAnimationOptions)option
{
view.alpha = 0.0; // make the view transparent
[self addSubview:view]; // add it
[UIView animateWithDuration:secs delay:0.0 options:option
animations:^{view.alpha = 1.0;}
completion:nil]; // animate the return to visible 
}

// remove self making it "drain" from the sink!
- (void) removeWithSinkAnimation:(int)steps
{
NSTimer *timer;
if (steps > 0 && steps < 100) // just to avoid too much steps
self.tag = steps;
else
self.tag = 50;
timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(removeWithSinkAnimationRotateTimer:) userInfo:nil repeats:YES];
}
- (void) removeWithSinkAnimationRotateTimer:(NSTimer*) timer
{
CGAffineTransform trans = CGAffineTransformRotate(CGAffineTransformScale(self.transform, 0.9, 0.9),0.314);
self.transform = trans;
self.alpha = self.alpha * 0.98;
self.tag = self.tag - 1;
if (self.tag <= 0)
{
[timer invalidate];
[self removeFromSuperview];
}
}


Before adding the code to put this into action, I want to explain the method in-depth.

This animation is based on progressive transformations applied a fixed number of times – each 1/20th of a second. It uses an NSTimer and stores the remaining steps in the Tag property (with Category we can only add new methods, not new objects/variables, so we use an existing one for keeping it simple). The right number of steps depends on how long you want this to last and how big your view is: you need some heuristic tests to find the right value.

At each step 2, CGAffineTransform (scale and rotate) are applied to the actual Transform property of the UIView, so that it’s reduced and rotated a bit. As a final effect, it’s also made a little lighter via Alpha Channel: in this way you’ll see your view quickly sinking while spinning, like someone took the stopper out of a sink full of water!

After the last step is done, the timer is invalidated and the view removed from the superview.

To see this in action, we just need to put one more button in ViewController and use the above animations.

Make the following changes to ViewController.h:


// Add to top of file
#import "FakeHUD.h"

// Add to method list
- (IBAction) btnHUD:(id)sender;


As always, implement it in ViewController.m:


- (IBAction) btnHUD:(id)sender
{
FakeHUD *theSubView = [FakeHUD newFakeHUD];
[self.view addSubviewWithFadeAnimation:theSubView duration:1.0 option:curveValues[selectedCurveIndex]];
}


In View in the MainStoryboard.storyboard, add a button with text “HUD” and connect the “tap up inside” event to (IBAction) btnHUD:.

Now you can run the app and enjoy!



Where To Go From Here?


Here is a example project with all of the code from the above tutorial.

UIKit provides quite a powerful way to animate views, and playing with the properties can give you some really cool effects with only a few lines of code. These effects are perfect for tool/utility-type apps, and adding them as categories of UIView makes your code more readable and lets you focus on your application logic.

I hope you enjoy your experimentations with UIView animations, and look forward to seeing you use them in your apps!

If you have any questions or comments about UIView animation, please join the forum discussion below!



This is a blog post by iOS Tutorial Team member Fabio Budai, an Objective C developer from Italy.

UIView Animation Tutorial: Practical Recipes is a post from: Ray Wenderlich