Build an iOS app using the IBM Mobile Data for Bluemix service

21 August 2014
PDF (810 KB)
Share:
author photo - kevan holdaway

Kevan Holdaway

Software Engineer, IBM Mobile Cloud Services

Find me on LinkedIn

author photo - belinda johnson

Belinda Johnson

Software Engineer, IBM Mobile Cloud Services

@BeeMarieJohnson

author photo - nick gibson

Nick Gibson

Software Engineer, IBM Mobile Cloud Services

@ndgibs on Twitter
Follow me on Google+

Sign up for IBM Bluemix
This cloud platform is stocked with free services, runtimes, and infrastructure to help you quickly build and deploy your next mobile or web application.

You may already know about some of the benefits of Bluemix, IBM's open platform for developing and deploying mobile and web applications. The many pre-built services in Bluemix make it easy for developers to build and enhance applications. In this tutorial, we'll show how to build an iOS application using the IBM Mobile Data for Bluemix service.

Have you ever gone to the grocery store and forgotten the exact ingredient your spouse needed for that fabulous soufflé recipe? Or the lunchbox dessert the kids had requested for the next day? What if they all could enter their requests into a shared grocery list, and you could receive push notifications alerting you to the updates?

Enter the BlueList application. It’s a simple iOS app to which we'll add the IBM Mobile Data for Bluemix service to store, delete, update, and query objects stored on the cloud. A future tutorial will show you how to add the Push and CloudCode services, so you can get notifications when the list is updated (Push service), and so the list can be refreshed on all devices when one of the devices updates the list in some way (CloudCode service).

This simple app uses Bluemix services and will get you started writing your own (more complex) apps in no time.

The bluelist-base(v0) code is the base version of the BlueList app. We'll show you how to add the IBM Mobile Data for Bluemix service, so that your code will look like the bluelist-mobiledata(v1) code. You can start with bluelist-base(v0) and walk through the steps, or jump ahead by downloading bluelist-mobiledata(v1) directly. The bluelist-mobiledata(v1) version of the BlueList app includes the IBM Mobile Data for Bluemix service.

What you'll need for your application

 
  • A basic familiarity with iOS development. The Apple Developer tutorial "Start Developing iOS Apps Today" describes how to install Xcode and write a basic application.
  • The bluelist-base(v0) code. Click the button above, then import and build the bluelist-base-iOS code into your development environment. Run this code in your emulator. Restart the application, and notice that the list items do not persist. The steps in this tutorial will show you how to add the IBM Mobile Data for Bluemix service to your app, so that list items will persist.
  • A Bluemix ID, so you can get the IBM Mobile Data for Bluemix service.
  • Optional: Familiarity with CocoaPods. The CocoaPods framework manages library dependencies for Xcode projects, and will automatically import required dependencies for the BlueList app. A Podfile specifying the dependencies is provided in the project root directory. Please familiarize yourself with the instructions to install and use CocoaPods.

Step 1. Create a Mobile Cloud application on Bluemix

 
  1. Log in to Bluemix.
  2. Click Add an application to go to the catalog. Screen shot of the Create an Application button
  3. Click Mobile Cloud, under Boilerplates. Screen shot of the Mobile Cloud boilerplate
  4. Click Create Application. Screen shot of the Mobile Cloud Application with the create application button
  5. Fill in the "Finish Adding Mobile Cloud " panel by selecting a space and choosing a name for your app. Then click Create. Screen shot of the Create an Application button
  6. After you create the application, it will appear in your dashboard. Click your new application to go to its Overview page. Screen shot of the Create an Application button

Step 2. Install and configure SDKs

 

Note: You may skip steps 1 through 6 if you instead choose to install the SDK Framework files using the CocoaPods method. This would involve running the Podfile included with the sample, according to the CocoaPod instructions in the prerequisites.

  1. You will see the Overview for your new application. Once there, click Download SDKs.
    Screen shot of the Download SDKs button

    Note: You'll need this Application ID later in these instructions.

  2. You will see the documentation for building a mobile application. Once there, click iOS SDK.Screen shot of the Download SDKs button

    Click to see larger image

  3. In Finder, locate the IBMBluemix framework (<unzipped_location>/IBMBluemix.framework). Drag this framework into the BlueList Xcode project under the Frameworks folder. Screen shot of the framework files going into the project
  4. Check "Copy items into destination group's folder (if needed)".
  5. In Finder, locate the IBMData SDK Framework. Drag this framework into the BlueList Xcode project under the Frameworks folder as you did with the IBMBluemix framework.
  6. Modify the bluelist.plist file so it contains the applicationId, applicationSecret, and applicationRoute values available on the application Overview page. (To get to the Overview page, go to the Download SDKs page by logging into Bluemix, going to your Dashboard, and clicking the desired application.) Screen shot of the Application in the Catalog
  7. Note: When creating a new iOS application using XCode, you must add the -ObjC and -lsqlite3 linker flags to the build settings. To do this, select the application's target and click the Build Settings. From there you can search for "Other Linker Flags." If you don't see this, make sure you have selected "All" settings and not "Basic". We have already added the flags into the sample project for you. Screen shot of the project's Xcode build settings.

    Click to see larger image

Step 3. Modify code to leverage the Data service

 
  1. Open IBM_Item.h. Review the current code.
    #import <Foundation/Foundation.h>
    
    @interface IBM_Item : NSObject
    
    @property(nonatomic, copy) NSString *name;
    
    @end
  2. Change the super class to IBMDataObject and have the IBM_Item conform to the IBMDataObjectSpecialization protocol. Conforming to the IBMDataObjectSpecialization protocol will instruct the compiler that you will implement the IBMDataObjectSpecialization methods in your IBM_Item class.
    #import <Foundation/Foundation.h>
    #import <IBMData/IBMData.h>
    
    @interface IBM_Item : IBMDataObject <IBMDataObjectSpecialization>
    
    @property(nonatomic, copy) NSString *name;
    
    @end
  3. Implement the dataClassName method, and mark the title property as dynamic. Also register the specialization in the class method initialize. This creates a mapping between the IBM_Item Objective-C class and the JSON class "Item" that is persisted in the cloud.
    #import "IBM_Item.h"
    
    @implementation IBM_Item
    
    @dynamic name;
    
    +(void) initialize
    {
       [self registerSpecialization];
    }
    
    +(NSString*) dataClassName
    {
       return @"Item";
     }
    
    @end

Step 4. Hook the Bluemix iOS SDK and IBM Mobile Data for Bluemix service into the application delegate

 
  1. First, read the application ID from the plist file you edited earlier.

    Click to see code listing

    #import <IBMBluemix/IBMBluemix.h>
    #import <IBMData/IBMData.h>
    #import "IBM_AppDelegate.h"
    
    @implementation IBM_AppDelegate
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        
        NSString *applicationId = nil;
        NSString *applicationSecret = nil;
        NSString *applicationRoute = nil;
        
        BOOL hasValidConfiguration = YES;
        NSString *errorMessage = @"";
        
        // Read the applicationId from the bluelist.plist.
        NSString *configurationPath = [[NSBundle mainBundle] pathForResource:@"bluelist" ofType:@"plist"];
        if(configurationPath){
            NSDictionary *configuration = [[NSDictionary alloc] initWithContentsOfFile:configurationPath];
            applicationId = [configuration objectForKey:@"applicationId"];
            if(!applicationId || [applicationId isEqualToString:@""]){
                hasValidConfiguration = NO;
                errorMessage = @"Open the bluelist.plist and set the applicationId to the Bluemix applicationId";
            }
            applicationSecret = [configuration objectForKey:@"applicationSecret"];
            if(!applicationSecret || [applicationSecret isEqualToString:@""]){
                hasValidConfiguration = NO;
                errorMessage = @"Open the bluelist.plist and set the applicationSecret with your Bluemix application's secret";
            }
            applicationRoute = [configuration objectForKey:@"applicationRoute"];
            if(!applicationRoute || [applicationRoute isEqualToString:@""]){
                hasValidConfiguration = NO;
                errorMessage = @"Open the bluelist.plist and set the applicationRoute to the Bluemix application's route";
            }
        }
  2. Make a request to initialize the SDK and IBMData service. Add this directly after the reading from the bluelist.plist file in IBM_AppDelegate.m

    Click to see code listing

        if(hasValidConfiguration){
            // Initialize the SDK and Bluemix services
    		[IBMBluemix initializeWithApplicationId:applicationId  andApplicationSecret:applicationSecret andApplicationRoute:applicationRoute];
            [IBMData initializeService];
        }else{
            [NSException raise:@"InvalidApplicationConfiguration" format: @"%@", errorMessage];
        }
        return YES;
    }
    
    @end

Step 5. Modify the IBM_ListViewController class to list and persist data from the MBaaS Data service

 
  1. Modify the listItems, createItem, updateItem, and deleteItem methods (IBM_ListViewController.m) to persist the item changes to the MBaaS Data service.
    - (void)listItems: (void(^)(void)) cb
    {
    	IBMQuery *qry = [IBM_Item query];
        [[qry find] continueWithBlock:^id(BFTask *task) {
            if(task.error) {
                NSLog(@"listItems failed with error: %@", task.error);
            } else {
                self.itemList = [NSMutableArray arrayWithArray: task.result];
                [self reloadLocalTableData];
                if(cb){
                    cb();
                }
    
            }
            return nil;
            
        }];
    }
    
    - (void) createItem: (IBM_Item*) item
    {
        [self.itemList addObject: item];
        [self reloadLocalTableData];
        
        [[item save] continueWithBlock:^id(BFTask *task) {
            if(task.error) {
                NSLog(@"createItem failed with error: %@", task.error);
            }
            return nil;
        }];
        
    }
    
    - (void) updateItem: (IBM_Item*) item
    {
        self.editedCell.textLabel.text = item.name;
        [[item save] continueWithBlock:^id(BFTask *task) {
            if(task.error) {
                 NSLog(@"updateItem failed with error: %@", task.error);
            }
            return nil;
        }];
    
    }
    
    -(void) deleteItem: (IBM_Item*) item
    {
        [self.itemList removeObject: item];
        [self reloadLocalTableData];
        [[item delete] continueWithBlock:^id(BFTask *task) {
            if(task.error){
                 NSLog(@"deleteItem failed with error: %@", task.error);
            } else {
                [self listItems: nil];
            }
            return nil;
        }];
        
        // Exit edit mode to avoid need to click Done button
        [self.tableView setEditing:NO animated:YES];
    }

Step 6. Run the app

 
  1. Now that you've made all the code changes, your code should now be equivalent to version 1, and your list items should persist!
  2. Run the code in the iOS Simulator or on your iOS device. Screen shot of the first page of BlueList app
  3. Add a couple of items to the list.

    Screen shot of adding items to the list
  4. Now pick one item and edit it by clicking it.

    Screen shot of editing an item
  5. Save the item you edited. It should now be modified in the list view.
  6. Restart the application.
  7. Notice that your data items have persisted. You now have data persisted to the cloud!

Step 7. See your data on the cloud

 
  1. Log in to Bluemix.
  2. Click your application in the Dashboard view.
  3. Click the MobileData Service.
  4. On the Manage Data tab, you can see Data Classes being stored in the cloud, as well as the instances of each Data Class being persisted. Screen shot of data viewer
  5. On the Analytics tab, you can see various analytics data for your application, including total API calls by device, API calls by type, and amount of storage used. Screen shot of analytics statistics and graphics

    Click to see larger image

Conclusion

 

Developing this app using the MobileData service available in Bluemix should give you a sense of how easy it is to consume and integrate mobile data capabilities using mobile cloud services!


RELATED TOPICS:IBM Mobile Data for Bluemix service (Android app)

Add a comment

Note: HTML elements are not supported within comments.


1000 characters left

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Mobile development, Cloud computing
ArticleID=963139
ArticleTitle=Build an iOS app using the IBM Mobile Data for Bluemix service
publish-date=08212014