Using the IBM MobileFirst Platform for iOS on IBM Bluemix (Part 2 of 2)

In my last blog post, I documented the steps required to create a simple iOS app using Xcode and the Swift programming language. In this post, I take you through the steps required to alter this mobile application to leverage the Cloudant NoSQL service on IBM Bluemix as a data store.

We use IBM MobileFirst Platform for iOS to access the Cloudant NoSQL data store on IBM Bluemix. Using the IBM MobileFirst Platform of iOS, we get access to a number of services on IBM Bluemix;

  • mobilefirstSDK for node.js
  • Cloudant for NoSQL DB
  • Push iOS 8
  • Advanced Mobile access

In this post, we’ll use the Advanced Mobile Access and Cloudant for No SQL DB services only. To get started, let’s create a new mobile application on IBM Bluemix.

  1. From the IBM Bluemix Dashboard select CREATE AN APP
  2. Select MOBILE then select iOS8
  3. Details of the MobileFirst Services Starter will display, click on CONTINUE
  4. Provide a unique application name, then click on FINISH

You’re presented with the Advanced Mobile Access (AMA) Dashboard and are asked to configure your client application.

  1. Enter the Bundle ID and Version number of the Xcode project that will leverage our Cloudant NoSQL db. If you’re using the iOS app from my previous post, the Buncle ID is com.ibm.ContactList and the version is 1.0
  2. We’ll install the IBM MobileFirst Platform for iOS SDK manually,  but for now copy & save the pod file values as given, you’ll need these later
  3. Change the snippet tab to Swift (the language used to create the ContactList app in my last post), copy the snippet value and save for use later

We’re done with IBM Bluemix for now. Let’s now move our attention to our attention to our Xcode environment on Mac.

Install the IBM MobileFirst Platform for iOS SDK on Maccocoapods

If you haven’t already, go ahead and install CocoaPods. To install CocoaPods open a terminal window and issue the following commands;

sudo gem install cocoapods
pod setup

With CocoaPods installed, you can go ahead and create a Podfile in your Xcode project folder. Open the Podfile in a text editor and paste in the values saved above. If working with the ContactList project from my last post, we don’t require all dependencies, so can edit your Podfile to look like this;

source 'https://github.com/CocoaPods/Specs.git'
# Copy the following list as is and remove the dependencies you do not need
pod 'IMFCore'
pod 'IMFURLProtocol'
pod 'IMFData'

Save and close the Podfile, then from your terminal window issue the following commands;

pod install
open App.xcworkspace

Your project will open in the Xcode IDE. Note: you can find the instructions above with a little more detail on the IBM Bluemix Docs site, see here.

Update your iOS app to leverage the Cloudant NoSQL service as a data store on IBM Bluemix

cloudantAt this point I’ll assume you’re working with the ContactList app developed in my previous post. I’ll detail the changes required to allow this app leverage the Cloudant NoSQL service on IBM Bluemix.

First, we need to update the AppDelegate class to initialise the IBM MobileFirst Platform for iOS SDK. Use the code copied above and paste into the application method. Note to resolve dependencies, also include an import for IMFCore in the AppDelegate class.

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        IMFClient.sharedInstance().initializeWithBackendRoute(backendRoute, backendGUID: backendGuid)

        // Override point for customization after application launch.
        return true
    }

Next we need to update the ContactListModel class – that class we use to represent contact details and the objects we’ll use to store on Cloudant. In summary; we update the class to extend from NSObject and CDTDataObject; we change our class attributes to be of type NSString; we include an init method. I’ve included the code for the ContactListModel class below;

import Foundation
import CloudantToolkit

    class ContactListModel: NSObject, CDTDataObject {
        
        //Required by the IMFDataObject protocol
        var metadata:CDTDataObjectMetadata?
        
        var firstName: NSString
        var lastName: NSString
        var number: NSString
        
        init(firstName: String, lastName: String, number: String) {
            self.firstName = firstName
            self.lastName = lastName
            self.number = number
        }
        
        var contactInfo: String {
            return "Name: \(firstName)" + " \(lastName) " + "Number: \(number)"
        }
        
        override convenience init() {
            self.init(firstName:"", lastName:"",number:"")
        }       
}

Our final step in modifying the ContactList app is to update our ViewController to create a remote data store, then save any new contact added in this data store. Note: this app is very simple, we don’t even read back contact details from our remote data store. I’m simply outlining the bare bones of storing data in a Cloudant NoSQL db from an iOS app in this post.

In our addContactTapped method I include the code to; create a remote data store; set the type of data we’ll be storing; save a newly added contact in a remote store. I’ve included the relevant code below;

        //Get reference to data manager
        let manager = IMFDataManager.sharedInstance()
        let name = "contactdb"
        
        // Create remote store
        manager.remoteStore(name, completionHandler: { (createdStore:CDTStore!, error:NSError!) -> Void in
            if nil != error {
                //Handle error
                println("Yikes ! Store issue")
            } else {
                var store:CDTStore = createdStore
                println("Successfully created store: \(store.name)")
                
                //Set the data type of the objects we'll store in our remote store
                store.mapper.setDataType("ContactListModel", forClassName: NSStringFromClass(ContactListModel.classForCoder()))
                
                //Save a new contact to the remote data store
                store.save(contactList, completionHandler: { (savedObject:AnyObject!, error:NSError!) -> Void in
                    if nil != error {
                        //Save was not successful, handler received an error
                        println("Save was not successful")
                    } else {
                        // Use the result
                        println("Saved revision: \(savedObject)")
                    }
                })

            }
        })

Launch our updated app from the Xcode IDE to open the iOS Simulator. Add a new contact via the simulator. This will invoke the code to create a new remote store. The contact we just tried to add won’t be added to the store however, as we have one final thing to do and that’s to sort the permissions on the contactdb in the Cloudant NoSQL store.

Update Permissions on Cloudant

Open the IBM Bluemix console in your browser, then open the mobile application created earlier. Click on the Cloudant NoSQL DB service to open, then select Cloudant Dashboard. You should see the contactdb listed, click on this, then click on Permissions. Grant all permissions to ‘Everybody Else’ then try and add another contact via the app. You should be able to see that a new record has been created in the db via the Objects and Documents option in IBM Bluemix.

The source for the updated ContactList application is available on IBM DevOps Services for Bluemix, You can clone a copy of the Git repository using the following URL; https://hub.jazz.net/git/rodalton/ContactListMF

So there you have it. With just a few simple steps we can alter an existing iOS app to leverage a Cloudant NoSQL DB on IBM Bluemix. The steps are straight forward and surprisingly easy. Hope you found this post useful, feel free to contact me on Twitter @daltonology

 

Advertisements
Leave a comment

1 Comment

  1. iPhone app development with Xcode and Swift (Part 1 of 2) | All Things Cloud

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: