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”


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.