Fat Fractal Tutorial for iOS: Getting Started

Learn how to make an iOS app with a back end like Twitter in this beginner Fat Fractal tutorial!

Version

Other, Other, Other

Mobile backend services, also known as BaaS (Backend-as-a-Service), have become very popular these days because they save you a ton of time and money when it comes to developing an app that needs a remote database.

In the time since Antonio wrote that article, there’s a new game in town! It’s called Fat Fractal, and we’re big fans.

Fat Fractal offers a number of advantages over other back-end providers, and in this tutorial we’re going to give you some hands-on experience with it so you can see if it’s right for you.

Keep reading to learn more about Fat Fractal, and how it stands out from other service providers like Parse!

Why Fat Fractal?

I have used Parse, Stack Mob, and recently a few months ago, Fat Fractal to write apps for my iOS consulting company. There were always something that didn’t feel quite right when using Parse or Stack Mob.

Data modeling. Providers like Parse force you to use their own objects called PFObjects. This made me feel uncomfortable as I like to define my objects as subclasses of NSObject, instead of having extra overhead or lock-in in case I decide to change backend providers.

Querying for data. Some extremely simple queries, if you are writing your own backend, turn into unimaginably complex API calls when using services like Parse. I remember writing an Instagram-like app for a client which had to make over 10 (!) separate API calls to the backend to just retrieve a profile page, when using Parse. This adds to alot of round trip requests and slow loading times.

Server-side extensions. Way too much code that should be executed on the server, are instead being done on the iOS client. This is because the lack of control and access you have on the backend on services like Parse and Stack Mob.

So how does Fat Fractal stack up with regards to the rest of the BaaS providers? Let’s hear it from the founders of Fat Fractal themselves:

Compared to other BaaS, Fat Fractal is better thought through, and does not end up being a frustration at some point when you want to do something hard. The focus is on not limiting a developer in any way.

Also, Cory Wiles, a long-time iOS developer and BaaS enthusiast, has two blog posts about his experience with Fat Fractal which you can read here and here. Also, you can find his recent BaaS comparison reports – lots of extremely detailed information here, definitely worth checking out!

Here is a quote from Cory on why he loves Fat Fractal:

“Over the past 2 years I have used various BaaS services (Parse, Stackmob, Kinvey) with production apps and where I hand-rolled my own webservices using RDBMS, as well as NoSQL, which are not just ‘hello world’ tutorials. Each one has its niche in the market; but when making the decision of which service I would use for developing WhoNote, and any future applications, FatFractal is the clear choice.

I am able to keep clean, native objects easily, define a complex object-graph, implement proper server-client design with extensions, event handlers, scheduled tasks and last, but not least, have configurable implicit and explicit permissions while developing in an exact duplicate, local, development environment that I then push to the cloud. FatFractal is the next evolution of app development platforms.”

So with that, here is a tutorial for you to try out Fat Fractal for yourself, and see how it can help you reduce server-side complexities as an iOS developer!

Getting Started

In this tutorial, you will be building a social networking app similar to Twitter – but implemented 100% by yourself. :]

Your app will allow users to posts short messages like “tweets”, follow/unfollow other uses, and see “tweets” from users that they have followed.

Most of the heavy lifting and data querying will be done by the server backend, so you would need a robust BaaS service provider like Fat Fractal to do so.

So let’s create an account! Head over to Fat Fractal and click Login / Register:

Fill in your email and the password you want, and follow the instructions there after to get your FatFractal account.

Check your email for a verification link to complete activation of your account. Click on the link and log in to your account.

You will be redirected to a welcome page, with a big button that allows you to Add a new Domain. Click that:

In the form that appears, fill in the name of the domain you want. For this tutorial, I am using rwtweet as my domain name. You will have to use something else. The description is optional and you can fill in anything you want.

Next, add an application to your domain by clicking on Add a new application:

Choose NoServer for Type, No Server Sandbox for Subscription, the domain you entered earlier, and then name the app the same as your domain. You can give it an optional description if you would like as well.

Click Create, and you are done! You now have a fully working application and backend running in the cloud – though you can’t interact with it just yet ;)

Installing FatFractal Locally

Next, you will install FatFractal locally on your computer. For those of you who have experience with web development, you are probably familiar with developing and testing your web applications locally before deploying them to the cloud. Sadly, most BaaS do not support this feature, which means that you are always developing in production – which is dangerous.

Luckily, FatFractal supports local development, which you can then push to the cloud and ‘live’ your code when you are satisfied. This is one of the key strengths of FatFractal – the ability to build your backend locally, which is much faster, efficient and safer than compiling, deploying and tweaking over the internet. As their webpage states – “You are installing a fully featured FatFractal Engine on your desktop. This is not a crippleware version, not a simulation.” Check this link out for more information.

Once the download is complete, unzip the file to a location of your choice, preferably your Home directory. You are now going to add the FatFractal_Runtime/bin directory to your path. This allows you to run command line instructions without referencing the full path. Open up Terminal, and type in nano ~/.bash_profile as such:

Press Enter, and you should see your bash_profile, which may have other lines of code in it. Add the following to the bottom of your file (do not touch any of the other lines!): export PATH=/(your FatFractal installation directory)/FatFractal_Runtime/bin:$PATH

Save and exit by pressing Control-X and pressing Y and Enter when prompted if you want to save your changes.

Restart Terminal at this point so it picks up your new path changes.

Next, you are going to scaffold your application backend. Scaffolding an app creates a directory structure with essential files needed by the backend so that the application can be deployed to the engine. Create a new directory for your application and change to it inside Terminal:

> mkdir rwtweet
> cd rwtweet

Scaffold your application using the ffef command – but replace the bracketed entries with what you entered for your domain name and app name in FatFractal. For example, I used rwtweet for both.

> ffef newapp [YOUR DOMAIN NAME] [YOUR APP NAME]

Note: FatFractal requires Java JRE1.6 to run. If you don’t have it installed already, it will be installed automatically after you issue this command.

Fat Fractal will then generate a scaffolded application for you:

At this point, your application backend is ready to be deployed. Deployment delivers your scaffolded backend to a FatFractal Engine for execution in the cloud.

So let’s deploy your backend application to the cloud right now! Deploy your application with the ffef command:

> ffef deployFFFabric

You should be prompted for your email and password, you will have to answer Yes to the question “Would you like to validate your domain[rwtweet] and context[rwtweet] before deploying to the FatFractal Cloud?” and will see something like the following in your Terminal:

After your Terminal reads Done, head over to .fatfractal.com/ and you should see something like this:

Congratulations – you have successfully deployed your backend to the cloud!

Now it’s time to set up your iOS client and write some Objective-C code.

Downloading the SDK and Starter Project

Before you can set up the iOS Client, you need to download the FatFractal iOS SDK. This will allow your application to easily interface with the FatFractal backend. Head over to http://fatfractal.com/prod/docs/getting-started/ and download the FatFractal iOS SDK.

If you unzip the file you downloaded, you should get a folder named FFEF.framework. Remember where you unzipped this file – you will need it soon.

Next, download the starter project I prepared for you. This starter project has the user interface pre-created so you can focus on the Fat Fractal-related code in this tutorial.

Open the project in Xcode and build and run. The first thing you will see is a login screen, as well as two buttons that lead to a Sign up and Log in page:

However, there is no backend or logic to handle this yet, you’ll create these functions shortly.

Before you proceed any further, have a look at the structure and flow of the app by opening MainStoryboard.storyboard.

The project starts from a root view controller called Tab Bar Controller. It has only one tab for now, the UINavigationController which houses the MainFeedViewController – a table view controller.

This MainFeedViewController will be responsible for showing all the tweets from your users. It will look something like the real Twitter iOS application – but not quite as colorful.

The WelcomeViewController is the landing page for users who have not logged in or signed up yet. It is a modal view controller that is presented by the MainFeedViewController, hence it is not directly linked to any controllers in the storyboard. It is supposed to be similar to the Twitter landing view when you first download the app and launch it.

The color here could also use a little work. :] But anyways, this WelcomeViewController will link to the SignupViewController and LoginViewController respectively for the user to authenticate themselves with the backend web service.

Ok, so now that you are oriented around the application, you can begin configuring your project to work with FatFractal!

Setting Up The iOS Client

When done, test that your Xcode project is able to build with the FFEF.framework linked in by building the project (Build or ⌘B). Everything should run without error. If so, this means that your app is integrated with the FatFractal SDK. You are now ready to work with the service!

The next logical step is to create some sample objects as a sanity check, and to finally see your backend in action!

Creating Sample Objects

The cool thing about FatFractal is that it uses native Objective-C classes for its backend data modeling. This is your object definition. The FatFractal platform does not create dependencies in your code by requiring you to use their own proprietary object classes like most other BaaS. (PFObject anyone?)

This prevents vendor lock-in, which means that you do not have to rewrite your entire application – models, controllers and all if you ever decide to migrate backend service providers. Pretty thoughtful of the folks at FatFractal!

Lets create your first test object – a TestZombie class that you will solely use for testing purposes.

Choose File > New > New File or ⌘N to bring up the Template Chooser for the new class file. You will use the standard Objective-C class template. Click Next.

Enter the name of the Objective-C class, TestZombie, as a subclass of plain old NSObject. Then click Next and then Create and Xcode will add TestZombie.h and TestZombie.m files in your project.

Here you create three properties – one for the zombie’s name, one for its gender, and one for its mortal enemy – like shotguns!

Because in Xcode 4.5, properties are automatically synthesized for you, you can leave the TestZombie.m file alone.

That’s it for the test object model – let’s create an instance of the main class you will use to work with FatFractal.

Adding The FatFractal Instance

To work with Fat Fractal, you need to create an instance of a class named FatFractal that comes in the FFEF framework you added earlier.

You will instantiate the FatFractal as a singleton in the AppDelegate class. This is to ensure there is only one instance of FatFractal living in your application at any one time – any reference to it will be grabbed from AppDelegate.

You first have to import the header file from the FFEF framework. Because you will be using the FatFractal class in many places – let’s import it in your Tweetie App-Prefix.pch file which will automatically import in this framework for all your files.

Open Supporting Files\App-Prefix.pch and add this file to import the FFEF header:

#import <FFEF/FatFractal.h>

Then switch over to AppDelegate.m, and add the following below your import statements:

Here you’ve created a new instance of the FatFractal class, passing in the URL for the app you created earlier. You also turn debug mode on so you can see some verbose log messages.

Next, you added some test code to make sure Fat Fractal is working. Here you log in with a fake test user, create an instance of a zombie, and add it to your back end database. You’ll learn more about how all this works later on.

Finally, add the declaration for your ff method to AppDelegate.h:

+ (FatFractal *)ff;

Once done, build and run. If all succeeds, you should see a mess of debug statements in your console log, but the most important statement you will see is highlighted:

It reads, “statusMessage : Created new resource /ff/resources/TestZombie/…”. This is a HTTP response from the web server to let you know that the POST request to create an object was successful, along with other meta-data that you will analyse in Part Two.

Let’s not take your console log’s word for it, and do a manual check on the web service to see that your object is really created. Head over to your web service’s URL at http://.fatfractal.com//ff/resources/TestZombie to check it out. My URL is http://rwtweet.fatfractal.com/rwtweet/ff/resources/TestZombie. You should see something similar to the following:

What you see is the JSON data containing the details of the TestZombie object you just created. Walking Dead fans will approve!

You realize that you were able to create your own object classes without having to use third party object models. Simply by passing in your native Objective-C data structure, it creates your object’s data model on the backend for you.

Sweet! Now comment out the test code you just added, since you won’t be needing that anymore:

About FFUser

On the FatFractal platform, there is a special object called FFUser that represents users. It behaves exactly like any other object, except for some predetermined properties.

By default, Fat Fractal is set to auto-register a user upon first log in. This means when a user tries to log in, if the username does not exist already Fat Fractal automatically creates a new an FFUser object with two properties: userName and password.

You saw an example of this earlier – in the test code, it logged a test user in with a certain username and password even though you never explicitly created that user. Behind the scenes, Fat Fractal automatically created a FFUser object for you.

By default, a user has read and write permissions on every object they create. Also by default, every registered user has read permissions on every other users’ objects, but not write permissions. Unregistered users may not create objects on the backend, but may read anything with public read permissions.

Most of this default behavior for FatFractal serves your needs fine for now, except for one. You don’t actually want Fat Fractal to auto-register users, like you saw in the test code. Instead, you want them to go through your sign up process first.

Inside your rwtweet directory (the one you created earlier with the Fat Fractal scaffolding), search for and open ff-config/application.ffdl. For those of you who are using TextMate, you can just cd into tweetie directory and type

> mate .

When you open application.ffdl, you should see multiple lines of configuration code. You want to edit the AllowAutoRegistration value:

Change the value from true to false, like this:

Save the file. Go to Terminal and deploy your new settings to your application in the cloud. Type in your Terminal:

> ffef deployFFFabric

If prompted if you would like to validate your domain again, key in No (N).

Building The Authentication System

Next let’s build your authentication system.

Open SignupViewController.m, and add the following code to signupButtonPressed: right after the “TODO” comment:

Then inside checkForAuthentication replace the line if (false) { with the following:

if ([AppDelegate checkForAuthentication]) {

This checks to see if the user is logged in, and if not presents the WelcomeViewController.

And with this, you can now sign up new users for your application! >Build and run and try to sign up a new user. You should see the modal Welcome View Controller dismiss itself and show you your MainFeedViewController table view if successful.

Not bad for just a few lines of code, eh?

Building The Authentication System Part II

Let’s complete the rest of the authentication system while you are at it.

Open AppDelegate.m, and let’s make the application automatically log in the user if there are user credentials in the keychain.

Inside application:didFinishLaunchingWithOptions:, add the following code after the “Login with FatFractal by initiating connection with the server” comment:

Calling the loginWithUserName:AndPassword:onComplete method on your FatFractal instance, which will return with a response from the server.

If there is an error, your keychain item is probably corrupted. Thus, you will clear it, and force the user to sign up and log in again when he next launches the application. In a production application, more robust error handling can be done.

If there is no error, and the server returns you an FFUser object, you will send a message to the MainFeedViewController to inform it that user is successfully authenticated. This is so that you can know when to download the tweets and user information, as well as refresh the table view in the MainFeedViewController.

Build and run your application. If all goes well, in the log you should see the FFUser object being returned by the server and your log message that login from the app delegate using keychain was successful:

The Login View Controller

Registration works great, but the Login View Controller still doesn’t work, so let’s add the code for that next.

Open LoginViewController.m and add the following code to loginUserWithUsername:andPassword: after the “TODO” comment:

Calling the loginWithUserName:AndPassword:onComplete method on your FatFractal instance, which will return with a response from the server.

Handle the error, if any. Notice that you do not display the localized error, you will explain why in a short while.

Check that the server actually returned you the FFUser object, save your credentials in the keychain and dismiss the modal view.

Now, why don’t you show the localized error message?

The reason is that the error message will reveal that the user is either using an incorrect password or user name that does not exist. This is bad in terms of security as you don’t want to make it easy for people to guess user names or passwords. Thus, you give a generic message that makes it hard to guess if the user name exists or the password is wrong. You can see it in the logs below:

For now, you will not be using the Login View Controller, as you are automatically logged in when you sign up, and there is no log out function as of yet.

You will come to that in a while.

Adding Your First Tweet

What Twitter clone would you have if the user can’t even post his or her tweet?

Let’s create the Micropost object that will hold your tweets.

Choose File > New > New File or ⌘N to bring up the Template Chooser for the new class file. You will use the standard Objective-C class template. Click Next.

Enter the name of the Objective-C class as Micropost, a subclass of NSObject.

You first check if the user is logged in, and create a new Micropost object with the text and currently logged in users as the properties.

You then call the createObj: method on your FatFractal singleton to create and post the object to your web service. This should be familiar to you by now.

The interesting thing here is the onOffline: block.

Fat Fractal supports offline queuing for most operations, in case the client is offline. The Fat Fractal SDK will try to complete any queued operations every 1 second while the client is online, and every 10 seconds while your client is offline.

The queued operations are saved to the iOS device local storage, so they survive app restarts, termination etc. This is very useful when designing an app like Twitter, which if your user tweets a post while in an area without network connectivity, the app will ‘hold’ or queue the post for you, and post it to the server when the user has connectivity again.

Allright! The last step is to display the new Add Tweet View Controller modally from the Main Feed View Controller.

Open MainFeedViewController.m and import the file:

#import "AddTweetViewController.h"

Then open MainStoryboard.storyboard and drag a UIBarButtonItem from your Object library to the navigation bar of your Main Feed View Controller like this:

Change the Identifier of the UIBarButtonItem under the Attributes Inspector to Add.

Next, connect the UIBarButtonItem you added to the AddTweetViewController through a modal segue by Ctrl-Dragging from the button to the AddTweetViewController:

And select Modal Segue when the pop up appears:

Allright! Run the app now try adding a tweet.

To do this, click on the + Bar Button, and you should see the AddTweetViewController’s modal view appear. Type in what ever you like, and hit the Tweet button:

You should see something like the following in your logs, signifying that your post was successful!

If you go to your Fat Fractal domain, using your web browser, at https://[YOUR DOMAIN].fatfractal.com/[YOUR APP NAME]/ff/resources/Micropost, you will see that your object has been created in your backend, along with other JSON data:

Our table view is still empty though.. So let’s retrieve this data and format it to your table view.

Retrieving And Displaying The First Tweet

Open MainFeedViewController.m, import your Micropost.h file:

#import "Micropost.h"

Next, you need an array to hold all the posts that you download from the web service, and a property to keep track of your current user. Change the @interface directive inside MainFeedViewController.m to look like this:

Basically, what you are doing here is to check if there is a logged in user. If there is, you will assign the currentUser to the currently logged in user, as well as refresh the table with the new data from your backend.

Call this method from both viewDidLoad and userIsAuthenticatedFromAppDelegateOnLaunch:

You will check if the postsArray instance variable exists. If so, you will remove all objects from it and set it to nil. You then create the postsArray again.

To retrieve data from your FatFractal backend, you just need to call getArrayFromUri: on your singleton, and pass in the URI endpoint for the data you want to retrieve. In this case, it is /Micropost. This will retrieve all the objects from https://.fatfractal.com//ff/resources/Micropost for us.

Remember to call the refreshTableAndLoadData method in your callback too, so that this method will be invoked when you log in from the App Delegate.

Where To Go From Here?

In this part, you learnt how to set up the Fat Fractal backend, use the Fat Fractal iOS SDK, how to build your own authentication system, post data to the backend, and retrieve this data from the backend.

But there’s a lot more to learn with Fat Fractal! I could show you how to extend this app even further to allow users to follow each other, upload images, and more – demonstrating some neat functionality about Fat Fractal along the way.

If you would like to see more about Fat Fractal, please let me know! Otherwise, if you have any questions or comments, please join the forum discussion below.