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 🙂