Swift and Backend – Simple Tutorial

Since Apple released Swift’s source code, there’s been a big variety of interesting projects making good use of it’s openness. One category that has became pretty popular is application servers.

Why backend? Well, I believe most iOS developers would be pretty happy to use the same language and logic that it’s being used on their apps on the backend as well. There are some alternatives for Objective-C, but they never really took off.

Like I said, there’s a lot of options for an application server written in swift, so it begs the question : “Which one should I use?”. My personal opinion is: “It doesn’t really matter right now”. This is a brand new category for a brand new language, and dare to say, not one of them are production ready. I’d say to just pick one you think it’s easy to use, has a nice set of APIs and you think you can learn from it, and hopefully, contribute to it. I believe we’re still learning what Swift can do, and moving away from the iOS ecosystem is a very interesting way to expand your knowledge about it’s possibilities.

Swift Express

Swift Express is the one I’ve chosen to take a look at. My reasons:

  • I was able to make it up and running faster than heating my Pizza ( =~ 15min );
  • I found a bug on it and the developers were really fast in fixing it.

Hello World Tutorial

Their GitHub page is very simple to understand, and this tutorial is literally taken from their page, but I want to write here as well just to show how simple is to get it up and running with a few set of commands.


  • First, install Homebrew if you haven’t already.
  • Open your terminal and type the following commands:

brew tap crossroadlabs/tap
brew install swift-express

  • That’s it, it’s installed.

First Project

  • On your terminal, type the following commands:

swift-express init HelloExpress
cd HelloExpress
swift-express bootstrap

  • This is going to generate a Xcode project for you, everything ready to go just waiting for your code.
  • Open the Xcode project (HelloExpress.xcodeproj in this case), and add a method on your main.swift file


app.get("/myecho") { request in
    return Action.ok(request.query["message"]?.first)
  • Now run the commands on your terminal:

swift-express build
swift-express run

That’s it, your server should be up and running, to check if everything is fine, open your browser with the link : http://localhost:9999/myecho?message=Hello


Is Swift on the backend something that you’ll add to your project right away? Probably not, but all these projects are on their infancy and are pretty interesting already. I really recommend taking a look in at least one of them to broaden your Swift knowledge, it’s a nice way to start learning swift and maybe even give back to the community helping on the project development.


Git submodule tutorial – Cocoapods might not be the solution.

Recently I’ve been in lots of discussions about git submodule Vs cocoapods, and I noticed that, unfortunately, lots of developers never tried submodules, like the normal flow nowadays is to just go directly to cocoapods. Lots of arguments on why cocoapods is better are actually something that git submodules also does very well, like “semantic versioning”. Truth be told, I don’t think cocoapods is all bad, but I do think it tries to solve problems that doesn’t exist and add new issues in the process.

Some reasons I don’t like cocoapods:
– It’s *very* intrusive.
– It adds a dependency to your project (The irony);
– It adds problems that you wouldn’t have using other solutions;
– You have to wait for cocoapods support when you try new things (Swift, Xcode Beta, etc);
– If you want a different config from the one cocoapods generates, you’re going to have a bad time.
– Way more cumbersome to maintain forks;
– Too much “behind the scenes” configs;
– Very slow compared to git submodules;

But to be fair, there are some positive notes:
– Easier to add an external lib to your project;
– If you don’t like to configure the project your way, it will just do it for you;
– Easier to see what dependencies are outdated;
– Easier to try a lib and discard it;

In my opinion the disadvantages of it succeeds the advantages by a large amount. I never thought “Man, adding a new lib/framework to my iOS project sure is tedious and time-consuming, I wish there was a way to improve it” simply because I think it’s very fast to do it manually and it doesn’t compromise the control you have over *your* project.

This is my justification on writing this post, I just want to show how simple and easy is to use git submodule, a well supported, simple, non intrusive and robust way to add third party libs to your project, without adding any new dependency (Assuming you’re using git).

How does it works?
It’s pretty simple actually, just imagine that the git submodule is nothing more than another git repo inside your own repo. This is particularly good when you work on both projects (main and submodule) because the workflow is basically the same, when you want to work on the submodule project, the way you add,commit,push files is everything you already know and love.

On this tutorial I’ll create a simple Xcode project and add AFNetworking to it. I’ll assume that you already have a git repository up and running with your Xcode project, so I’ll skip these steps and go right to the submodule part.

Cool, you have your project, and you want to add AFNetworking as a submodule, right? Easy, what I like to do is to create a folder on my project structure to host all my submodules, making it easier to find the dependencies. So, let’s create the folder: (Assuming you are in the root level of your project)
mkdir -p Frameworks/External

Now, the *hard* part, adding the submodule:
git submodule add git@github.com:AFNetworking/AFNetworking.git Frameworks/External/AFNetworking

That’s it, the submodule is now added to your project, if you look at your root folder, you’ll see that now you have a new file called “.gitmodules”, if you open it you’ll see something like this:

[submodule "SubmoduleTutorial/Frameworks/External/AFNetworking"]
path = SubmoduleTutorial/Frameworks/External/AFNetworking
url = git@github.com:AFNetworking/AFNetworking.git

This is the config of your submodule, simple, easy to understand what’s going on, no mystery.

Now, the  final step is to just add the files you want from AFNetworking to your project, how you want it, whatever way you think is best, no auto config, no hidden settings.

What I like to do is to just add a group called Frameworks and drag the folder there:


That’s it, basically the entire list of steps are:
– git submodule add (repo url) (local path);
– Add files you want to your project;
– Done;

You can see on my github link how the submodule is represented by a link:
(https://github.com/Bunn/Git-Submodule-Tutorial/tree/master/SubmoduleTutorial/Frameworks/External) that goes directly to the host page. Pretty cool, right?

Of course, this is just scraping the surface of what can be done with submodules, but I just wanted to show how simple is to add a submodule to your project.

And later, if you want to clone your repo (or any repo that has a submodule) there’s just one extra step.
git submodule update --init --recursive
This is your “pod install”, but it’s incredible fast compared to the cocoapods alternative (The recursive flag is optional, as you might think, it’s just to get submodules of submodules if that’s the case, but it’s a rare scenario).

This is the link of the repository I used for this tutorial: (Submodule Tutorial)

As I said before, cocoapods is not all bad, but I really think developers should give it a try to git submodule because I’m pretty sure it will solve 90% of problems without adding yet another project dependency. Also, it’s way smarter to decide if it’s better to use cocoapods or submodules once you have at least the bare minimum experience with both approaches so you can weight the options and make the best decision. I’m not a cocoapods hater, as all technologies, cocoapods is just a tool that you need to consider to solve your problems, but I do believe lots of developers think that it’s the only option out there where it’s not true, there’s already a pretty solid solution ready to go with their git repo.
Here’s a link of the oficial documentation ( Documentation )

Also, while we are on the subject, I strongly recommend this read, an awesome post about having to think a bit before adding third-party libs to your apps.

Android emulator is too slow. And here’s the solution…

Why can’t we have nice things?

I’m an iOS developer, and anyone else who worked with iOS knows that iOS Simulator is awesome. Fast, reliable and pretty. Sure, sometimes it doesn’t work very well, but it’s pretty close to perfect. I would add some other features, such as, using your Mac’s iSight as a camera for the simulator. -Apple? Please?-

Needless to say that to someone who it’s used to work with iOS Simulator, the Android Emulator is a *very* big disappointment. But why is the Android Emulator so bad compared to the iOS Simulator?

Emulator vs Simulator

The terminology is: Simulator is a system that behaves similar to something else, but the implementation it’s not necessary the same. An Emulator in the other hand, is a system that behaves exactly like something else. Basically:

– iOS Simulator: Runs native code on you Mac, compiled for x86 architecture.

– Android Emulator: uses QEMU to run ARM, emulating the hardware.

Click here for an interesting reading about the subject.

Enters AndroVM

You can improve the experience using AndroVM and VirtualBox. In a nutshell, AndroVM is a VirtualBox Android image ready to use, and works pretty well 😉

– First open AndroVM download page clicking here and download androVM_vbox86p_4.1.1_r6.1-20130222-gapps-houdini-flash.ova file. (if you want the tablet version, download the vboxtp version.

– Download and install VirtualBox for your system clicking here.

– On VirtualBox, go to File -> Import and select the .ova file you just downloaded.

Import .ova

– I like to clone the image, so I can mess around with the system without any problems, so, right-click on the virtual machine and select “clone” and when prompted, select “full clone”.


– Right click on the image, click on Settings. Open the Network tab, click on Adapter 1, check the “Enable Network Adapter” and attach to your adapter. This is for “adb” to connect to your virtual box image.


– Now just run your machine and play around with the device, compare it with the standard emulator and see how fast it is 🙂


How to debug your application

Now that you have your VirtualBox setup, it’s time to actually use it to debug your apps. First, on your Android Emulator, open the AndroVM app. It should be the lower left icon on your device screen. You should see the device network IP there.


– Open your eclipse project, for this example, I just created a standard “Hello World” project.

– Open the “Run Configurations” panel, click on “Target” tab. Select to “Always prompt to pick device”.

– Run your project, you should see this screen


– Now, open your terminal, and type “adb connect THE_IP_OF_YOUR_DEVICE”

– After doing that, note that the Eclipse prompt now shows your device on the list.


– Select your device and click “OK”.

– That’s it, you should see your app running on your brand new emulator 😉



This is definitely not as fast as the iOS Simulator but it’s a huge step forward. With this setup you don’t need to always have thousands of devices with you neither wait hours to have the emulator to boot up.


– If you want to use the Android back physical button, hit “Esc”

– If you want to use the Android menu physical button, hit “F1”

Enjoy 🙂

WWDC 2011 Countdown iPhone app

Yeah, I know, I’m really busy and didn’t have time to create another post, hope to have time to create another one soon, if you have any ideas for the next post, please, leave a comment with your request.

Horray, I’m going to WWDC 2011

YEY! Yes, I was lucky enough to buy the ticket before it ran out, horray! And since I can’t wait for it, I developed some simple WWDC 2011 countdown app, so I can count the seconds for it. I assume that the opening will be at 10:00AM PST, same as last time, but there’s no official opening time that I know about it.

Anyway, this is the app screenshot, and if you want to install in your device, fell free do download the source code here. Fell free to modify, change, and do whatever you want with this project.

See you there 🙂

Where am I? Know how to get your location using CLLocationManager

Yey, here I am again. I didn’t update my blog for a while, I was really busy with some projects, hmm, in fact I’m busy right now, but I want to write a new post \o/.

One thing that’s really useful and simple to do using the iOS SDK is getting the user location to do whatever your want (well, not whatever you want, stalkers, but you got it). So, we will need something to help us out to get the user location, giving a quick look at the documentation you can find the CLLocationManager Class.

The CLLocationManager class defines the interface for configuring the delivery of location- and heading-related events to your application.

And let’s see, how do we use this class? Take a look at the example bellow:

locationManager = [[CLLocationManager alloc] init];

locationManager.desiredAccuracy = kCLLocationAccuracyBest;

locationManager.delegate = self;

[locationManager startUpdatingLocation];

Yep, that’s it, 4 lines of code and the locationManager now is looking for your location, pretty cool huh? You may ask “What is this desiredAccuracy property?”, well you should look at the documentation, it’s there for answer all our questions about the universe, but I’ll be a nice guy and copy it here

“You should assign a value to this property that is appropriate for your usage scenario. In other words, if you need the current location only within a few kilometers, you should not specify kCLLocationAccuracyBest for the accuracy. Determining a location with greater accuracy requires more time and more power.”

This property determines the precision of your CLLocationManager, it’s a const with 6 possible values, you should look at every one and use the one that best fits your needs.

OK, now our locationManager is updating your location, but how do we retrieve it? If you read the code carefully you may have seen that there’s a delegate assigned to self, right? This is how we will get our location. There’s 2 important delegate methods:

– (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation ;

– (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;

The second one is used in case of some error, for some reason your device failed to retrieve your location, and the first one will give you the CLLocation, that has the latitude and longitude plus other cool things. This delegate will be called every time that the locationManager gets a new (and better) location

That’s all you need to get the location of the user, but latitude and longitude are boring, OK, not really lat and lng rocks \w/, but let’s do something more useful with them…

One More Thing…

We have the location, latitude and longitude, with a few lines of code, but let’s transform this in a real address so it’s human readable. Again, reading the documentation we will find the MKReverseGeocoder

“The MKReverseGeocoder class provides services for converting a map coordinate (specified as a latitude/longitude pair) into information about that coordinate, such as the country, city, or street. A reverse geocoder object is a single-shot object that works with a network-based map service to look up placemark information for its specified coordinate value.

And how it works? It’s pretty similar to the CLLocationManager class, just 3 lines of code and the reverse geocoded starts the job

reverseGeocoder = [[MKReverseGeocoder alloc]  initWithCoordinate:currentLocation.coordinate];

reverseGeocoder.delegate = self;

[reverseGeocoder start];

And just like the CLLocationManager, we need to implement the delegate to get the address, and they are:

– (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark ;

– (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error;

The first delegate will return the MKPlacemark, that has the address, so you can access the thoroughfare with the property thoroughfare like placemark.thoroughfare.

I did a sample project that search for the user location and when it finds the location the MKReverseGeocoder start to search for the user address. In my example I have a condition that the reverse geocoded will only begin if the locationManager finds a location with accuracy range of 200 meters.

if (currentLocation.horizontalAccuracy <= MINIMUM_DISTANCE) {

[self startReverseGeocodingWithCurrentLocation];


Download the Source Code Here.

Have fun 🙂

UIScrollView and Zoom

UIScrollView and Zoom
As I wrote on my last post, this one would be a simple tutorial with UIScrollView and Zoom, right? OK, let’s create a new View-based Xcode project and name it Zoom.
Open the ZoomViewController, and create your UIScrollView in the loadView method.
– (void)loadView {
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
scroll.backgroundColor = [UIColor blackColor];
scroll.delegate = self;
image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@”image.JPG”]];
scroll.contentSize = image.frame.size;
[scroll addSubview:image];
scroll.minimumZoomScale = scroll.frame.size.width / image.frame.size.width;
scroll.maximumZoomScale = 2.0;
[scroll setZoomScale:scroll.minimumZoomScale];
self.view = scroll;
[scroll release];
What’s being done here is:
  • Creating a UIScrollView with the same size as the main screen
  • Setting the background color to black
  • Assigning the delegate to self
  • Creating an UIImageView with  a image that’s already added on the project, don’t forget to declare the UIImageView on your .h file.
  • Setting the contentsize to the full size of the image
  • Adding the image to the UIScrollView
  • Setting the minimum zoom scale to fit the iPhone screen horizontally, so the image with the lowest zoom level, will fit the screen
  • Setting the maximum zoom to be 2 times the image size
  • Setting the UIScrollView to start with the minimum zoom scale
  • Assigning the UIScrollView to the UIViewController’s UIView
  • Releasing the UIScrollView
OK, with that ready there’s only one thing missing here, we have to implement a UIScrollView delegate method called
– (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
And what does it do? Simple, just go to the documentation and you’ll see : “Asks the delegate for the view to scale when zooming is about to occur in the scroll view.” So, all we need to do here is return our image, like so:
– (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return image;
pretty simple, huh?
That’s it, that’s all you need to do to have a simple and functional UIScrollView with zooming 🙂 But wait, there’s one more thing…

One More Thing

If you run your project, you may realize that the image is not on the center of your screen, even if you zoom, and here’s how you can center your view on UIScrollView while zooming. But no worries, I will help you out, just copy this method:

– (CGRect)centeredFrameForScrollView:(UIScrollView *)scroll andUIView:(UIView *)rView {
CGSize boundsSize = scroll.bounds.size;
CGRect frameToCenter = rView.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width) {
frameToCenter.origin.x = (boundsSize.width – frameToCenter.size.width) / 2;
else {
frameToCenter.origin.x = 0;
// center vertically
if (frameToCenter.size.height < boundsSize.height) {
frameToCenter.origin.y = (boundsSize.height – frameToCenter.size.height) / 2;
else {
frameToCenter.origin.y = 0;
return frameToCenter;
This method will receive your UIScrollView and the UIView that you are zooming and calculate the correct frame for your UIView and return a CGRect. All you have to do is call this method on your scrollViewDidZoom delegate, that’s get called everytime that there’s some zooming, and you are ready 🙂
– (void)scrollViewDidZoom:(UIScrollView *)scrollView {
image.frame = [self centeredFrameForScrollView:scrollView andUIView:image];;
Now enjoy your centralized UIView in your UIScrollView

UIScrollView – A really simple tutorial

It’s very common to have a large amount of data that we want to display on the iPhone/iPod, but there’s no way that we can fit all at the same time on the screen (even on the iPad), that’s one of the functionalities of the UIScrollView.

The UIScrollView it’s a very versatile class, you can handle zooming, panning, scrolling, etc, and I have no intention of explaining all the properties and delegates (well, if you want to know something about the UIScrollView, fell free to request it in the comments, just let me know =D ), the documentation itself is pretty good, so you should give it a look.

In this post I’ll create a very simple project with three scrollable UIViews just to get familiar with the UIScrollView, and in the next post I intend to do some simple zooming example. So, the next  post will be about the UIScrollView as well.

The basics:

IMO, there’s 2 very important properties in UIScrollView, the contentSize and the contentOffset.

The contentsize is the width and height of your content, it’s a CGSize and a property of UIScrollView, let’s say that you have an image that’s 500×500, it would not fit on the iPhone screen, right? So, set your contentsize to 500,500. If you want to add more scrollable space at the bottom or at the top, you can use the property contentInset.top and contentInset.bottom, so you can add some extra space without changing the contentsize. And why would you need these insets? Well, if you have a UINavigationBar or a UIToolBar, like the photos app, you will use this.

Every UIScrollView has a scroll indicator (it’s visible by default, but if you want, you can hide it with showsHorizontalScrollIndicator and showsVerticalScrollIndicator), to give an indication of how far in the content you are, and you can change where the indicator starts using the scrollIndicatorInsets.top just like the contentInsets.

The contentOffset is the point that is currently visible, this point represents the top left of your screen. The contentOffset discards the contentInsets, so it can happen that the contentInset is negative, that’s not a problem.

The only thing that you need to have a functional UIScrollView is the UIView that you want to display and the contentSize of this UIView, so let’s start coding…

Create a View-based Application and name it SimpleScroll. Again, I always use the Window-based Application for my projects, but let’s pick the View-based just to speed things up.

Go to your SimpleScrollViewController class, in the loadView method and create your UIScrollView, we will create it with the same width and heigh as the view from SimpleScrollViewController

UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
Enable the pagination
scroll.pagingEnabled = YES;

If the value of this property is YES, the scroll view stops on multiples of the view bounds when the user scrolls. The default value is NO.

Create all three UIViews
NSInteger numberOfViews = 3;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i * self.view.frame.size.width;
UIView *awesomeView = [[UIView alloc] initWithFrame:CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
awesomeView.backgroundColor = [UIColor colorWithRed:0.5/i green:0.5 blue:0.5 alpha:1];
[scroll addSubview:awesomeView];
[awesomeView release];

The most important part in this for is to understand the xOrigin. This will place every UIView exactly where the previous UIView has stopped, in other words, each UIView will start at the end of the previous one.

Set the UIScrollView contentSize
scroll.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);

The contentSize is just the sum of the widths of the three UIViews, if the width of each UIView is 320, and we have three UIViews, your contentSize width will be 920.

Add the UIScrollView to the SimpleScrollViewController UIView
[self.view addSubview:scroll];
[scroll release];
And you’re done 🙂
At the end, you should have something like this :
– (void)loadView {
[super loadView];
self.view.backgroundColor = [UIColor redColor];
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scroll.pagingEnabled = YES;
NSInteger numberOfViews = 3;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i * self.view.frame.size.width;
UIView *awesomeView = [[UIView alloc] initWithFrame:CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
awesomeView.backgroundColor = [UIColor colorWithRed:0.5/i green:0.5 blue:0.5 alpha:1];
[scroll addSubview:awesomeView];
[awesomeView release];
scroll.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);
[self.view addSubview:scroll];
[scroll release];
As you can see, I changed the background color of the SimpleScrollViewController UIView to red, just to make sure that you can distinguish the content of the UIScrollView.
That is the tutorial, pretty simple, huh? Now you can show all the data that you want on this small screen 😉 Next post I’ll write about how to enable zooming using a UIScrollView.

Automating UI Testing

Why test your app?

Every time that you change something in your code, you have to test it again, there’s a lot that can (and should) be done with OCUnit , but what should you do when you want to test the UI? It’s really boring and time-consuming doing it manually, wouldn’t it be great if you could create some script that do all this mundane job for you? Testing your app you will:
  • Avoid regressions
  • Increase your app quality, therefore your users satisfaction
  • Do something else while the script does the boring work
  • Test manually only those more interesting scenarios.

UI Automation

UI Automation is integrated with Instruments. What does it means? It means that you can use alongside other instruments and see exactly what’s happening with your app.
It’s only supported on iOS 4.x and the device must support multitasking. The simulator or the device can be used to run the tests.

Script language

UI Automation uses javascript to run the tests. I’m not sure why they choosed javascript for that, maybe there’s a lot of javascript developers around the world, compared to other script languages, but I would choose Python instead 🙂
Problem in sdk 4.0.1 and 4.0.2

There’s a bug when you try to run the test if you are using one of these sdk versions. To fix this is pretty simple, just run the following commands in the terminal
cd ~/Library/Application\ Support/iPhone\ Simulator/
ln -s 4.0.1 4.0
If you are using 4.0.2 just substitute it in the second command.

How to automate?

Every control in your application gets represented to UI Automation as an element. Some examples are:
  • Name: Accessibility labels gets translated into the name of your element
  • Value : Value of a control, text from a textfield, and so on.
  • Elements : Every element can contain zero or more elements,  like a tableview cells
  • Parent: Like elements, but one level back up


To know if the test has passed or not, use these commands :
UIALogger.logPass(“yet, it’s OK”);


It’s very important to log everything that you are doing during the test, the more you log, the better. Every time that you interact with a control, it’s good to log what it’s being done, so when you go back to the results, it’s easier to find the problem.
To log it very simples, just call:
UIALogger.logMessage(“Log this”);
Let’s say that you want to know how your app looks like after some interactions, well, it’s pretty easy, just take a screenshot with. EDIT: This only works on the actual device.


Ok, enough talking, let’s write a very simple test case (maybe, some other time I’ll create a more complex example for UI Automation)  that will press a button and check the result in the textfield.
First, create an View-based Application project, and in the View controller, create the button and textfield, something like this:
– (void)loadView {
[super loadView];
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchDown];
[button setTitle:@”Click me” forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:button];
textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width – 20, 30)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.textAlignment = UITextAlignmentCenter;
[self.view addSubview:textField];
– (void)click {
textField.text = @”MyTestApp”;
– (void)viewDidUnload {
[textField release];
textField = nil;
– (void)dealloc {
[textField release];
[super dealloc];
When you click the button, the text “MyTextApp” should appear on the textfield. Go ahead, build and run your app and see if everything is ok.
Now, create a .js file with the following content
app = UIATarget.localTarget().frontMostApp();
mainWindow = app.mainWindow();
button = mainWindow.buttons()[0];
var result = mainWindow.textFields()[0].value();
UIALogger.logMessage(“Will tap on button”);
if (result == “MyTestApp”) {
UIALogger.logPass(“yey, it’s OK”);
} else {
UIALogger.logMessage(“Button tapped”);
What this script is doing is, getting the mainWindow, tapping on the button, and checking the textfield value.
Open your Instruments app (command + space, and type Instruments), and you should see this screen :
Choose the Automation template. In the next screen, on instruments, select your javascript file:
Select your application, you can find it at your project folder, inside Build->Debug-iphonesimulator (if it’s a simulator build)
Press record on the instruments,the simulador should open running your app and see how the button is clicked automatically. The result should pass and this is what you will see:


You can test a lot of things, like create functions in your javascript, do some  scrolling, screen rotation, pinching, and so on, even the multitask feature can be tested with this approach. So, it’s a very cool feature to have and more important, to use. Remember that it’s a good practice to restore the app to its initial state when testing, so, let’s say that you add some value, at the and of this test, remove this value and move along with the other tests (Of course, only if this value will not be used in other tests) .It’s a shame that there isn’t any recorder tool, so you could just use the app and the script would be generated automatically, but hey, it’s better than nothing, right 🙂
There’s a lot of information on the Reference Collection , you probably should take a look. This was a very simple example, just to give you a hint how the UI Testing works.
Now that you know how to create some automated tests, you can use your spare time to do something nice, like developing more apps 🙂

NSLog: Logging Tips

Sometimes it’s way better to just use a simple log then debugging your app step by step. That’s when NSLog comes in handy.
There’s a lot of ways to use NSLog in your code, I’ll show some of my favorites.
int myInt = 1;
float myFloat = 2.3;
NSString *myString = @”Hello Log”;
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 40)];
NSLog(@”Int [%i]”, myInt);
NSLog(@”Float [%f]”, myFloat);
NSLog(@”String [%@]”, myString);
NSLog(@”Object [%@]”, myView);
This is how the log will look like:
Int [1]
Float [2.300000]
String [Hello Log]
Object [<UIView: 0x5c07950; frame = (0 0; 20 40); layer = <CALayer: 0x5c07920>>]
What I’m doing there is, logging an Int, Float, NSString and an UIView. As you can see I always add some brackets in the log, and why do I do this? That’s only to know exactly what’s being logged. Imagine that I have a NSString with some white spaces, I will not know that it has the white spaces unless I add the brackets. Here’s an example :
NSString *test = @”Test   “;
NSLog(@”log: %@”, test);
Result : log: Test

NSString *test = @”Test   “;
NSLog(@”log: [%@]”, test);
Result : log: [Test   ]

Logging CGGeometry

Now, let’s say that you want to log some CGRect, CGPoint or CGSize, just transform them into NSString with :

Log Macro

Here’s a cool tip, although I’m not a macro fan, there’s one that’ great for logging:
#define MYLOG(fmt, …) NSLog((@”File [%s] Method [%s] Line [%d]: ” fmt),__FILE__, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
and you can use exactly like an NSLog, like so :
MYLOG(@”Hello Log”);
What this will do is:
  • __FILE__ : file path and name.
  • __PRETTY_FUNCTION__ : name of the method.
  • __LINE__ : the line of the method
You can edit this macro as you please, remove or reorder the parameters. That’s how the output will look like :
File [/Users/user/Desktop/Log/Classes/LogAppDelegate.m] Method [-[LogAppDelegate application:didFinishLaunchingWithOptions:]] Line [25]: Hello Log
That’s some simple tips that I have to share about the NSLog, if anyone has anything else to add, please share it in the comments.
That’s it, thanks for all the fishes 🙂

iOS HelloWorld example

Horray, you’ve got your mac and your iPhone, and you want to write some code and see how it goes. You can find a lot of Hello World tutorials around the web, but I believe that 95% or those tutorials use Interface Builder, and I’m not a big fan of IB, because it does some “magic” behind the scenes, and IMO it’s really nice to know everything that’s happening within your app. IB is not useless, but let’s not enter on this topic (yet). I think that’s better to write your first app without IB so you can see what’s really going on.

If you haven’t installed Xcode yet, go to http://developer.apple.com/iphone/index.action and get it. This dmg will install everything that you need, iPhone SDK, iPhone Simulator, XCode, and a bunch of useful apps, like Instruments and so on. By default, Xcode will be installed on /Developer/Applications/Xcode.app, go there and open it (or just hit command + space and type Xcode on your spotlight).

Go ahead and create a new Xcode project. You’ll be prompt to choose some project templates, we can select View-Based Application, it has a ViewController already configured, but let’s choose the Window-Based Application. The Window-Based application is the simplest template that you can think of, it will give you a Windows and an UIApplicationDelegate that responds to UIApplication. These files are required in any iOS application, so, that’s why the Window-Based application is as simple as it gets.

Name the project Hello World and this is what you’ll get :

The template creates a lot of required files for you, but let’s focus on the HelloWorldAppDelegate.h and HelloWorldAppDelegate.m, but take a look in the main.m file, you can see that the UIApplication is being created there.

Open the HelloWorldAppDelegate.m file, and check the following method:

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// Override point for customization after application launch.

[window makeKeyAndVisible];

return YES;


This method gets called when the initial configuration of the app is done, and your app is ready to launch, so it’s there that you have to call your initials methods, like in this example, our UIViewController. You have to be careful in what kind of method you call in there, because if your app takes a while to respond it will be watchdogged. For example, if you call some method that requires a server response and the server does not responds back for a while, the iOS will kill your app, but let’s forget about this for now.

We could just add the label directly to the window, like so :

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// Override point for customization after application launch.

CGRect labelFrame = CGRectMake(50, 50, 200, 30);

UILabel *helloLabel = [[UILabel alloc] initWithFrame: labelFrame];

helloLabel.text = @”Hello World”;

[window addSubview:helloLabel];

[window makeKeyAndVisible];

[helloLabel release];

return YES;


IT’S DONE! Tutorial finished!

OK, sorry, that’s not true, I mean, you can do this, but you don’t want to do like this, believe me 😉

Let’s do it right, forget about the last piece of code, and let’s start again. Let’s create an UIViewController subclass, and add it to the window. It’s on the view controller that you will add your label, and whatever you need. Go to File -> New File (or command + N) and create an UIViewController subclass.

Let’s name it HelloWorldViewController like so:

Open the HelloWorldViewController.m, as you can see, you have the basic file structure all ready for your use (Hey, thank you, Apple guys). Search for the method named – (void)loadView, which is used to manually populate a view controller.

Let’s copy the same code that we use previously in the appDelegate

– (void)loadView {

UIView *mainView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];

CGRect labelFrame = CGRectMake(50, 50, 200, 30); 

UILabel *helloLabel = [[UILabel alloc] initWithFrame: labelFrame];

helloLabel.text = @”Hello World”;

[mainView addSubview:helloLabel];

[helloLabel release];

self.view = mainView;

[mainView release];


Let’s see what are we doing here :

  1. UIView *mainView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds; Creating our UIView with the same size of the main screen.
  2. CGRect labelFrame = CGRectMake(50, 50, 200, 30); The CGRect will be the bounds for your view.
  3. UILabel *helloLabel = [[UILabel alloc] initWithFrame: labelFrame]; This will create the UILabel class with the CGRect that we have created.
  4. helloLabel.text = @”Hello World”; Just set the string on the label text. Why add an @ at the beginning of the string? That’s to differentiate the NSString from the C String.
  5. [self.view addSubview:helloLabel]; Every UIViewController controls  a UIView (yey, it does makes sense, doesn’t it?), so, to access it you just have to use self.view and that’s it. Here we are adding the helloLabel (that is a UIView subclass) to the HelloWorldViewController UIView
  6. [helloLabel release]; Since we have added the helloLabel to the HelloWorldViewController UIView, we can release it, because the UIViewController will handle the memory management for the UILabel
  7. self.view = mainView; Adding out custom UIView to the UIViewController’s UIView.
  8. [mainView release]; The UIViewController now retains the reference to it’s UIView, so, we can release it.

We are almost done, just one more thing: we need to hook up our brand new UIViewController to the HelloWorldAppDelegate  and add it to our window.

To do it, go back to the HelloWorldAppDelegate.m and import our view controller class:

#import “HelloWorldViewController.h”

now, let’s create alloc and init our HelloWorldViewController:

HelloWorldViewController *helloController = [[HelloWorldViewController alloc] init];

add it to the window:

[window addSubview:helloController.view];

and release the HelloWorldViewController. Generally you will not want to release the view controller just yet, but in this example, there’s no problem:

[helloController release];

You will end up with something like this:

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

HelloWorldViewController *helloController = [[HelloWorldViewController alloc] init];

[window addSubview:helloController.view];

[helloController release];

[window makeKeyAndVisible];

return YES;


Build and run your project (command + enter), and your should see this :

Pretty simple, huh? Click here to download the HelloWorld example 🙂