Archive for the ‘Development’ Category

How to Get the Current Time with NSDate

December 7th, 2009

In iPhone app development, timing is everything. Being able to take a pulse on the current time is crucial to many apps, especially games. Fortunately, this can be done with as much ease as a developer would expect using the NSDate class in the iPhone SDK. Today’s iPhone development advent tip is another one-line wonder:

NSTimeInterval time = [[NSDate date] timeIntervalSince1970];

The timeIntervalSince1970 method returns the number of seconds since epoch. The return value type, NSTimeInterval, is a typedef of double, so you will have the necessary accuracy to get the current milliseconds from the first 3 digits after the decimal if need be.

How to Open the Mail App With a Pre-Composed HTML Email

December 6th, 2009

photo 2-1Have you ever wanted to open the Mail app with a pre-composed email? Then today’s iPhone development advent tip is the one for you! This has many uses, but a common one is a tell-a-friend feature in apps. If you attach the code from this tip to a button, you can give your users a way to promote your app to their friends via the iPhone’s built in Mail app.

A Handy Function

The sendEmailTo function, seen below, can be included in any class in your app. This function gives you a simple interface to send emails. It allows you to define “to” addresses, “cc” addresses, “bcc” addresses, a subject and a body. The body supports HTML tags.

- (void)sendEmailTo:(NSString*)to withCC:(NSString*)cc withBCC:(NSString*)bcc withSubject:(NSString*)subject withBody:(NSString*)body {
	NSString * url = [NSString stringWithFormat:@"mailto:?to=%@&cc=%@&bcc=%@&subject=%@&body=%@",
					  [to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
					  [cc stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
					  [bcc stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
					  [subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
					  [body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
 
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

NOTE: Running this function in the iPhone Simulator will have no effect because the simulator does not include the iPhone’s Mail app. To see the effects of this function, it must be run on a device.

Example Usage

Once you have that message defined in one of your classes, you can open the Mail app with a pre-composed email with just one message call. The following example opens an email and specifies a to, cc and bcc address. It populates the subject with “Addicus” and populates the body with a short message about Addicus that includes a link and an image (which is also a link). As you can see, this is done with good old HTML tags. This results in the email in the above screenshot.

[self sendEmailTo:@"mom@example.com"
           withCC:@"dad@example.com"
          withBCC:@"asecretfriend@example.com"
      withSubject:@"Addicus"
         withBody:@"<p>Check out this game, <a href='http://addicusgame.com'>Addicus</a>, for the iPhone and iPod Touch. It's super-addictive!</p><p><a href='http://addicusgame.com'><img src='http://getsetgames.com/wp-content/uploads/2009/11/icon_addicus.png'/></a></p>"];

If you would like to have the user specify the to, cc and bcc addresses themselves, as you would in the case of a tell-a-friend button, then you would call the following message:

[self sendEmailTo:@""
           withCC:@""
          withBCC:@""
      withSubject:@"Addicus"
         withBody:@"<p>Check out this game, <a href='http://addicusgame.com'>Addicus</a>, for the iPhone and iPod Touch. It's super-addictive!</p><p><a href='http://addicusgame.com'><img src='http://getsetgames.com/wp-content/uploads/2009/11/icon_addicus.png'/></a></p>"];

How to Load a UIImage From a URL

December 5th, 2009

Early on in development of Addicus, we discovered how easy it was to load images from the web. This was a huge boon to us since it meant our artists could modify assets on our server and they would update live in the test builds, without having to make a new build.

This all hinged on the ability to load a UIImage from a URL. And as it happens, this can be accomplished in as little as one line of code:

UIImage * img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://example.com/image.png"]]];

This eventually led to us writing a resource manager singleton class that handles all of our resource loading and can be toggled between local and web mode.

Eliminating class dependencies on your application delegate

December 4th, 2009

Ever have the need to call a method inside your app delegate from an arbitrary place in your code?  We’ve had to deal with this issue in a few cases working on our new project.  We’re making use of a UIScrollView instance to give us that popular flick scroll movement that is so popular on the iPhone.  We’ve found that alot of people have been interested in doing the same thing and you can read our blog on that particular challenge here.  We have a UIScrollView instance sitting inside our app delegate and there are certain parts of our code where we need to move that UIScrollView among different layers in Cocos 2D.  To do that we need access to the scroll view instance itself.  That results in code like the following…

myAppDelegate *app = [[UIApplication sharedApplication] delegate];
UIScrollView *appOverlayScrollView  = (UIScrollView *)app.view;
[[app window] sendSubviewToBack:appOverlayScrollView];

This creates a messy dependency between an arbitrary class and the app delegate class.  Wouldn’t it be great if we could send a message to the app delegate and tell it to move the scroll view to the front or back maintaining encapsulation?  Turns out you can indeed do this.  The UIApplication class contains a method called sendAction which is normally used to send an action message identified by a selector to a specified target.  This method can easily be used to call selectors in any object so the above code can be converted to…

[[UIApplication sharedApplication]
sendAction:@selector(bringScrollViewToFront)
to:[[UIApplication sharedApplication] delegate]
from:self
forEvent:nil];

The only downside to this approach is that I haven’t found a way to supply arguments along with the selector so you need to be calling a method with no arguments.  If you know of a way around this issue please do let me know.

How to Display an Activity Indicator with UIActivityIndicatorView

December 3rd, 2009

We all wish that our apps could run without latency and pauses, but the reality is loading screens are needed from time to time. Today’s advent tip is how to display an activity indicator in your app like the one seen below. It’s great for soothing the savage, impatient user.

ActivityIndicator

It can actually be done with just a few lines of code. First, we create and position the UIActivityIndicatorView by doing the following. It needs to be added to a view, so be sure to replace “myView” with your own view.

UIActivityIndicatorView *activityView = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
[myView addSubview: activityView];
activityView.center = CGPointMake(240,160);

So now the activity indicator is created and positioned but it isn’t visible yet. You can make it visible at any time by running the following one line:

[activityView startAnimating];

Finally, once you’ve finished loading the copious amounts of awesomesauce that fuel your app, you can make the activity indicator go away by running the following solitary line of code:

[activityView stopAnimating];

How to Show an Alert with UIAlertView

December 2nd, 2009

2

Showing an alert message to the user isn’t just a handy interface lick, it’s also an invaluable debugging tool. Thankfully, this functionality is built into the iPhone SDK.

To pop an alert with a title, message and OK button, we use the UIAlertView class like so:

UIAlertView *alert = [[UIAlertView alloc]
			initWithTitle: @"Announcement"
			message: @"It turns out that you are playing Addicus!"
			delegate: nil
			cancelButtonTitle:@"OK"
			otherButtonTitles:nil];
[alert show];
[alert release];

But what if you want to have more than one button on the alert and collect user input from it? Well that is pretty simple too. To do that, you first need to create a class that employs the UIAlertViewDelegate delegate like so:

@interface MyClass : NSObject <UIAlertViewDelegate>

Then, in your class, you need to override the alertView method in order to receive input like so:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 0) {
		NSLog(@"user pressed OK");
	}
	else {
		NSLog(@"user pressed Cancel");
	}
}

Finally, we create the UIAlertView and pass in the delegate. Also note that we’ve labeled the Cancel button “Cancel” and added the “OK” button to the other button titles, which differs slightly from the above example.

UIAlertView *alert = [[UIAlertView alloc]
			initWithTitle: @"Announcement"
			message: @"It turns out that you are playing Addicus!"
			delegate: MY_DELEGATE
			cancelButtonTitle:@"Cancel"
			otherButtonTitles:@"OK",nil];
[alert show];
[alert release];

How to Open a URL in Safari

December 1st, 2009

1Tis the season to broaden your iPhone dev chops! We have been developing on the iPhone platform for about 6 months now and it turns out that in that time, you tend to learn lots of little tips and tricks. Since we’re overcome by the spirit of giving around this time of year, we are going to be posting 24 of these bite-sized iPhone development tips, 1 every day between now and Christmas day. Consider it an advent calendar of iPhone dev tip goodies.

On With The First Tip!

Say you would like to open a URL in Safari. We used this on the “Get Set” button on the main menu of Addicus. Here is how to do it with just one line of code using the UIApplication class:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://getsetgames.com/"]];

The Next Game from Get Set

November 27th, 2009

We thought it would be fun to show you a little preview of our next game which is currently in production. It’s still early days on this project so I won’t get into the details but you can expect a lot of action from this title!

Get Set Games - Next Game

Social events in Toronto

November 22nd, 2009

A few weeks ago I had the opportunity to attend Joel Spolsky’s DevDays conference here in Toronto.   This was a one day conference covering a number of ideas in programming, design and software engineering.  It cost $100 to attend and while it had its shaky points overall it was worth it in my mind.  There are a few sites out there which have a nice overview of the event and the slides from each of the presentations.  If you missed it don’t worry it seems pretty likely Joel will be back next year.

While Joel’s event had very little to do with game development there are a bunch of social gaming gatherings you should be checking out right here in the Toronto area that do cater to the game developer/designer.

Hand Eye Society – You like talking about making games?  Playing games?  You should definitely be attending.  Their next event is Nov. 26th.  It will be highlighting the latest work from Shawn McGrath, Pekko Koskinen and Jon Mak.  The events take place in a bar called “Unit” just east of the Gladstone Hotel.  Full details are on the Hand Eye website.

IGDA Toronto Chapter – I’ve been attending these meetings off and on since 2001.  There are always an interesting collection of minds and ideas floating around.  The one downfall is that attendance can vary month to month and there has been the occasional slip up in communication where a meeting is canceled or re-scheduled.  There are the occasional presentations and lectures as well.  Be sure to check the website for all the latest news before deciding on attending and you’ll have no problems.

Unity Users Group – Very new.  I just attended the first one last week but it looks like they could be alot of fun.  Not sure when the next one will be but I will be sure to post about it on Twitter when it happens.

Ryan Creighton over at Untold Entertainment keeps a fancy calendar of all these events so be sure to check it out from time to time.  All of us here at Get Set Games have attended one or more of these events at some time or another.  If you make your way out to one of them send me an email (rob -at- getsetgames.com) and I will be more than happy to have you buy me a drink.

Automatically Insert Your SVN Revision Number Into Your Xcode Project

October 21st, 2009

Wouldn’t it be handy for your iPhone app to have access to its subversion revision number at run-time? Of course it would!

Being able to access the current revision number in your app is especially useful for testing. We use it to display the current rev on our test builds so our testers can reference the build that they discover bugs in, like so:

IMG_01632

Here’s how to do it

1. In Xcode, add an empty header file to your project’s “Other Sources” group called “revision.h”.

2. Add a “New Run Script Build Phase” to your target.

3. When defining your build phase, use “/bin/sh” for the Shell value and enter the following script:

REV=`svnversion -n`
echo "#define kRevision @\"$REV\"" > ${PROJECT_DIR}/revision.h

4. Ensure that the new build phase happens before your “Compile Sources” build phase.

5. Build your app.

That’s it! From now on you can use a string define called kRevision wherever you would like to reference your revision number at run-time.

IMPORTANT: Do NOT add your revision.h file to your subversion repository. It will be generated automatically each time you build your app.