This guide will help you to setup your development environment for AeroGear, and then build a simple application to verify the installation. The guide assumes that you have XCode IDE installed in your machine. If not, you can download it from the Apple developer web site here. Let’s get started.
Fire up Xcode and when presented with the welcome screen, choose "Create a new Xcode Project"
On the next screen, choose "Empty Application"
Enter "AeroGearExample" in the Product Name field and your initials as the Class Prefix. In this example I used "AG". For the device family I used iPhone. Leave the default options checked.
Xcode creates our project and we are presented with the default project screen.
Now that our project is created, its time to install required dependencies.
Generally, there are two approaches to install dependencies.
The first approach (and the preferred one) is to use CocoaPods dependency manager. If you haven’t used it so far in your iOS projects, please take the time to familiarize yourself. It will make your life much easier when dealing with dependencies (and upgrades!). Have a look at the web site for installation details.
The second approach, is to manually add the dependencies to the project. Both approaches are discussed in this guide, so peak the approach you are most familiar with.
In the "Podfile", add the following lines:
xcodeproj 'AeroGearExample.xcodeproj'
platform :ios, '5.0'
pod 'Reachability', '~> 3.0.0'
pod 'AeroGear', '1.0.1'
And then:
pod install
to install the dependencies.
NOTE: Don’t forget to open the Xcode workspace file instead of the project file after this step.
We need to download both AFNetworking and the AeroGear libraries from their respective sources.
For AFNetworking click here
For AeroGear click here.
Extract the zip archives and when finished, time to add them to our project.
First, we add AFNetworking. Click "File→Add files to AeroGearExample". In the dialog sheet that pops up, navigate to where AFNetworking code was extracted and select the AFNetworking folder
Make sure that "Copy items into destination group’s folder" and "Create Groups for any added folders" is checked.
Now time to add AeroGear library. Click again "File→Add files to AeroGearExample". In the dialog sheet that pops up, navigate to where AeroGear code was extracted and select the "AeroGear" folder.
Again, make sure that "Copy items into destination group’s folder" and "Create Groups for any added folders" is checked.
Now that our depenendecies are set up, it’s time to verify our installation. For this, we are going to build a simple application that will fetch the latest Tasks from the TODO application deployed on OpenShift. The tasks will then be displayed on a standard UITableView component. Let’s start.
1: Create your controller Create a new objective-c file, choose the name AGViewController, make it extends UITableViewController.
2: Link view and controller Click on the "AGAppDelegate.h" on the Project Navigator, add a property that link to AGViewController (don’t forget to import it).
#import <UIKit/UIKit.h>
#import "AGViewController.h"
@interface AGAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property(strong, nonatomic) AGViewController *controller;
@end
Click on the "AGAppDelegate.m", add line [1] and [2] to initialize the controller.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
self.controller = [[AGViewController alloc] initWithStyle:UITableViewStylePlain]; // [1]
self.window.rootViewController = self.controller; // [2]
[self.window makeKeyAndVisible];
return YES;
}
3: Implement AeroGear login and retrieve tasks
Now, click on the "AGViewController.m". First of all, import the "AeroGear" library [1].
Modify AGViewController implementation to add instance variables for authentication module [2] and for the task [3] returned from the server.
#import "AGViewController.h"
#import <AeroGear/AeroGear.h> // [1]
@interface AGViewController ()
@end
@implementation AGViewController {
NSArray *_tasks; // [3]
}
- (void)viewDidLoad {
[super viewDidLoad];
id<AGAuthenticationModule> authModule;
// NSURL object:
NSURL* projectsURL = [NSURL URLWithString:@"http://todo-aerogear.rhcloud.com/todo-server/"];
AGAuthenticator* authenticator = [AGAuthenticator authenticator];
authModule = [authenticator auth:^(id<AGAuthConfig> config) { // [4]
[config setName:@"myModule"];
[config setBaseURL:projectsURL];
}];
id<AGPipe> tasksPipe;
// create the 'todo' pipeline, which contains the 'projects' pipe:
AGPipeline *todo = [AGPipeline pipelineWithBaseURL:projectsURL]; // [5]
tasksPipe = [todo pipe:^(id<AGPipeConfig> config) { // [6]
[config setName:@"tasks"];
[config setAuthModule:authModule];
}];
[authModule login:@"john" password:@"123" success:^(id object) { // [7]
[tasksPipe read:^(id responseObject) { // [8]
_tasks = responseObject; // [9]
[self.tableView reloadData]; // [10]
}
failure:^(NSError *error) {
NSLog(@"An error has occured during fetch! \n%@", error);
}];}
failure:^(NSError *error) {
NSLog(@"Auth:%@", error);
}];
}
// the rest of your file ...
Let’s explain in more details, what we’re doing here:
Central to AeroGear is the concept of Pipeline and Pipe. The former represents a collection of server connections and the latter the connection itself.
In [4] and [5] we initialize our Pipeline and Authenticator objects. Both act a factory in which the former creates Pipe objects connected to remote endpoints, while the latter give us access to different authentication modules provided by AeroGear (such as Rest, Basic and Digest).
In [6] we call the "add" method on our pipeline and use the given code block to set the name of the remote endpoint (in our case "tasks") on the given AGPipeConfig object. In the config, we also link the authenticate module we described earlier. This will give us a fresh authentificated Pipe object to work with. Note that, if not specified in the add method, the pipe will use REST as its communication type. (More types are planned for ther future, such as websockets).
In [7] we send the login message, within the success callback issue a "read" request [8] on the Pipe to fetch the tasks from the remote application, passing a success and failure block. If the fetch was successful, we assign the return result to our tasks object [9]. Finally, we ask the tableview to reload itself to display the data [10].
4: RefreshView with data Time to fill the empty table data source methods that Xcode created automatically for us when we created the class, with code that renders the fetched data.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_tasks count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [[_tasks objectAtIndex:row] objectForKey:@"title"];
return cell;
}
5: Run it!
Ok we are now ready to run the project. Select "Product→Run" and if all goes well you will be presented with the following screen.
Success! Your first iOS application built with AeroGear!
You can download the source code of this project from github. For a more complete example application that uses AeroGear to perform CRUD operations on a remote endpoint, have a look at the TODO application available on github.
You can also browse AeroGear iOS API reference to familiarize yourself with the wealth of options.