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

 

iOS development with Xcode and Swift (Part 1 of 2)

I recently found myself with some time on my hands (after having surgery on my back :[ ) so figured I’d do some learning ! I was keen to explore iPhone app development with Swift and also interested in working with the mobile services available on IBM Bluemix. I took a modular approach to learning :]

  • I started by building a simple iPhone app to store contacts. I built the app using the Xcode IDE and the Swift programming language
  • With the app in place, I made the source available on IBM Bluemix DevOps Services
  • Finally, I modified the iPhone app to leverage the Cloudant NoSQL service on IBM Bluemix

In this blog post, I’ll go through the steps involved in building my simple iPhone app. You can use this post in isolation or as the first part of a two part series. In my next post, I’ll detail the steps involved in updating this application to leverage the Cloudant NoSQL service on IBM Bluemix as a data store.

Some background to my ContactList app

I’m not a Swift developer ! Far from it, this was my first attempt at creating an iPhone app with Swift, but found it straight forward so thought I’d share. I built the app with Xcode 6.3.1 on OS X Yosemite.  My app uses the Model View Controller (MVC) pattern to allow a user enter contact details (name & number), store this contact in memory using an array of contact objects and display an updated list of contacts back to the user. All data is stored in memory, kill the app and any data entered is lost. The purpose of creating the app was simply a learning exercise around object oriented programming with Swift. I used MVC not only to implement best practice, but also with extension in mind. I knew extending the app to leverage Cloudant as a data store would require the use of a model for objects that we’d persist on IBM Bluemix.

Creating a simple iOS app with Xcode

After launching the Xcode IDE, I created a new project. I used the Single View Application for iOS template.

xcode_template

I entered a Product Name, Organization Identifier and set the language to Swift.

xcode_project

Finally, I chose a directory and let Xcode create the project.

Next, I used Xcode to create a new file that I’d use to define my model (a model of a contact that would include a first name, last name and phone number). From Xcode chose File → New→ File, Select Swift File and click Next. I gave the file the name ContactListModel, then clicked on Create. I’ve included the code I used on the ContactListModel below;

    class ContactListModel {
        var firstName: String!
        var lastName: String!
        var number: String!
        
        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)"
        }

We’ll alter the code above in my next post as we store each ContactListModel in Cloudant rather than as a local array of objects.

Next, I defined my UI using Main.storyboard. I found the tutorial here very useful in understanding how to use the Interface Builder. The screen grab below outlines the elements of the UI.

contact_ui

  • First Name, Last Name and Number are all Labels
  • To the right of these labels are Text Fields
  • Add Contact is a Button
  • Below Add Contact is a Text View used to display the list of contacts

After building the UI, I modified the ViewController class to include a refreshUI method and an addContactTapped method to handle button click events. I’ve included the code of the addContactTapped method below;

    @IBAction func addContactTapped(sender : AnyObject) {
        let contactList = ContactListModel(firstName: firstNameTextField.text, lastName: lastNameTextField.text, number: numberTextField.text)
        
        contacts.append(contactList)
        
        //Build string to display in the results view
        var contactDetails = ""
        
        for contactList in contacts {
            contactDetails += contactList.contactInfo + "\n"
        }
        
        //Display content
        contactListView.text = contactDetails
        
        //Refresh UI
        refreshUI()
    }

You’ll see from the code above that each time the user adds a contact, I create a ContactListModel object, then add this to an array of objects to store and finally display details in a text view. Given this was a simple learning exercise, I didn’t implement any update or delete options. This is a bare bones, getting started app to look at the basics of Swift !

I’ve made the code available on IBM Bluemix Devops Services, if you’d like to pull down a copy, here’s the URL of the Git repository; https://hub.jazz.net/git/rodalton/ContactList

In my next post, I’ll start with the code on IBM Bluemix Devops Services and alter to work with a Cloudant NoSQL store on IBM Bluemix. For now, feel free to clone my project and open with Xcode. Hope you find this useful !

Inaugral Dublin PaaS & Bluemix Meetup

meetup
We delivered out first IBM Bluemix meetup in Dublin on Wednesday, 8 April. Working with some colleagues from IBM, Ben O’Sullivan and John Power, we set about organising this meetup in February 2015 and gave ourselves plenty of time to spread the word and sort logistics.

We scheduled our meetup to take place in the Ireland Computer Society HQ on Pembroke Rd in Dublin. The choice of venue was tough ! As this was our first Bluemix meetup, we were unsure whether to go with a less formal approach and host our meetup in a Dublin City pub. icsThe ICS premises turned out to be a great option however. The location was central and the facilities allowed us present a demo of Bluemix in a relaxed yet professional setting.

We had a good turnout for our first meetup with around 35 in attendance in total. The audience was a good mix of experienced developers and those keen to get started with Bluemix. Rafael Da Silva, another colleague from IBM, delivered a set of demos around IoT, Watson and devops. These practical examples of using the platform consumed most of the evening and provoked some excellent and sometimes challenging questions ! You can find some pictures from our meetup on meetup.com.

For our first meetup, I think it’s fair to say we got off to a pretty good start ! We learnt alot from this exercise and like all good agile practitioners, plan to iterate over our delivery model to refine and improve quality 🙂 We’re already in the process of planning a follow up both in Dublin and other locations (Galway in particular) in Ireland.

To learn more about IBM Bluemix, why not join one of the public webinars advertised here; http://webinars.mybluemix.net/

Feel free share any questions/comments you might have on IBM Bluemix meetups on Twitter;
Ben O’Sullivan @benosullivan
Rafael Da Silva @raphaelsilvada
Ronan Dalton @daltonology