Subscribe

Share

Application Development

Go Native with Apple iOS

Use the Oracle Mobile Cloud Service Apple iOS SDK to develop mobile apps.

By Chris Muir

May/June 2016

Oracle Mobile Cloud Service is designed to be mobile-client-agnostic, in that it will work with any mobile platform, including Android; Apple iOS; Windows; JavaScript for hybrid mobile solutions; and, of course, Oracle’s own Oracle Mobile Application Framework. The REST APIs published via Oracle Mobile Cloud Service can accept calls from any external mobile client technology that supports HTTP and REST.

But being client-agnostic doesn’t mean that there is no help for mobile developers on the various mobile platforms. Oracle Mobile Cloud Service provides native SDKs for several different mobile platforms. The SDKs are designed to significantly simplify and cut down on the amount of code needed to write raw REST and HTTP native calls to Oracle Mobile Cloud Service, often reducing 50 lines of raw HTTP and REST code for each call down to just 4 or 5 lines with the native SDK.

This article explores Oracle Mobile Cloud Service’s support for the Apple iOS platform to demonstrate how the Oracle Mobile Cloud Service client SDKs make coding native mobile apps easier. The coding approach for the iOS SDK provides a useful introduction to how all the SDKs work. The iOS SDK is written in Apple’s Objective-C, but I’ll show how the iOS SDK supports using Apple’s new Swift programming language.

Getting Ready

This article commences where the previous Oracle Magazine article on Oracle Mobile Cloud Service—“Offloading Mobile Storage”—left off. In the previous article, you created a mobile back end, OraMagTestBackend; two mobile users, joedoe and janeroe, with the same password, Welcome1*; and two storage collections, OraMagSharedCollection and OraMagIsolatedCollection, which you populated with the JSON files joesSharedJsonFile.json and janeSecretJsonFile.json, respectively.

This article shows you how to complete an iOS mobile application written in Swift to enable a mobile user to log in remotely to Oracle Mobile Cloud Service, view the list of objects stored in OraMagSharedCollection, and finally view the contents of each selected object, as shown in Figure 1. The code to do this demonstrates various Oracle Mobile Cloud Service iOS SDK API calls to help you understand how the SDK works.


o36mcs-f1
Figure 1. Sample application

For the iOS mobile client, you will need an Apple Mac with OS X 10.10+ and Apple Xcode 7.2+ installed. You should also download the Apple Xcode source code for the“ starter application that accompanies this article, unzip the source code archive to your desktop, and open the .xcodeproj file in Xcode.

Note that the starter app can be run immediately in iOS Simulator; by default, it shows the login page with fields for the user’s credentials. The actual Oracle Mobile Cloud Service logic has not yet been added, but if you log in with a dummy username and password, you will be able to view the empty list of storage items and return to the login page by clicking the Logout button to get an understanding of the application’s flow before integrating API calls to Oracle Mobile Cloud Service.

Preparing an iOS App for Oracle Mobile Cloud Service

The Xcode starter app is already loaded with the Oracle Mobile Cloud Service iOS SDK. The steps for loading and configuring the iOS SDK are covered in detail in the MCS: 11. Configuring the MCS SDK on iOS Oracle Mobile Platform YouTube video.

As part of the steps to configure the iOS SDK, it is necessary to configure the OMC.plist file within the Xcode project with the identifiers for the OraMagTestBackend mobile back end you created earlier in Oracle Mobile Cloud Service. The entries in the OMC.plist file instruct the SDK how to contact Oracle Mobile Cloud Service on the mobile app’s behalf at runtime. To configure the OMC.plist file, follow these steps: 

  1. On your desktop in your favorite browser, log in to Oracle Mobile Cloud Service and open the Settings page of the OraMagTestBackend mobile back end you created in the previous article. Note the various identifiers on the page, as shown in Figure 2. In the following steps, you will copy these into the OMC.plist file.

    o36mcs-f2
    Figure 2. Mobile Backends Settings page
     
  2. Disable the OAuth Consumer authentication option. You will rely on HTTP Basic authentication in this instance, to restrict the scope of this article.
  3. In the Xcode project, double-click the OMC.plist file and expand all the nodes, with the exception of the OAuth node (which you won’t use because you disabled OAuth authentication).
  4. Copy the Base URL, Application Key, Mobile Backend ID, and Anonymous Key to the respective baseUrl, appKey, mobileBackendId, and anonymousKey key values in the OMC.plist file. Be careful not to accidentally include spurious white spaces or new-line characters.
  5. Update the MyBackend key value to OraMagTestBackend/1.0.
  6. Finally change the authenticationType value from Oauth to Basic and the logLevel value from info to debug. Figure 3 shows an example OMC.plist file in Xcode populated with values from an Oracle Mobile Cloud Service instance.

    o36mcs-f3
    Figure 3. An example configured OMC.plist file

The Oracle Mobile Cloud Service iOS SDK is written in Objective-C. It can also be used in apps built with Swift. Note in the Xcode project the presence of the OraMag03_Bridging_Header.h file, which has been appropriately referenced in the project’s Objective-C Bridging Header build-setting option. This makes the SDK libraries available to the Swift compiler.

Completing the MCS Login Page

Within the Xcode project’s Main.storyboard, the login view controller provides a login page with a username field, a password field, and a Login button. The corresponding LoginViewController.swift file includes the doLogin() method wired to the Login button as well as logic for checking if the username and the password are nil. However, the code is missing the logic for authenticating your mobile user against Oracle Mobile Cloud Service. Let’s complete that logic now:

  1. Open the LoginViewController.swift file, and locate the doLogin() method.
  2. Under the line comment // <<MCS CODE #01>>, replace the dummy if 1 == 2 statement with the following code block:
    let mcsMbeManager: OMCMobileBackendManager = 
    OMCMobileBackendManager.sharedManager()
    let mcsMbe: OMCMobileBackend = mcsMbeManager.defaultMobileBackend
    let mcsAuthorization: OMCAuthorization = mcsMbe.authorization
    let loginError: NSError! = mcsAuthorization
    .authenticate(usernameStr, password: passwordStr)
    if loginError != nil {

This code makes use of the Oracle Mobile Cloud Service iOS SDK libraries. The first and second lines are typical SDK calls. The OMCMobileBackendManager class provides a handle for retrieving an instance of the default mobile back end at runtime. This is what you configured in the OMC.plist file earlier.

The code then attempts to authenticate the user with the given username and password from the login page, making a remote authentication call to Oracle Mobile Cloud Service’s user management services API. A “not-nil loginError” indicates a failed login attempt, whereas a “nil loginError” indicates a successful authentication. From here you can navigate to the storage page.

Coding the login page is no more complicated than this. A relatively complicated set of raw HTTP and REST code to do remote authentication becomes four or five lines of code with the Oracle Mobile Cloud Service SDK.

Retrieving a List of Objects from the Collection

Having built the login page, let’s move on to the storage page. The storage page is designed to show a list of objects available for the current authenticated mobile user from the OraMagSharedCollection you created in the previous Oracle Magazine article. The storage page already contains an iOS table view that displays the retrieved objects from the collection as rows as well as a slidable action on each row to display the contents of the selected object in the table.

Unlike in Oracle Mobile Application Framework, you can’t simply drag and drop a data control onto the page in Xcode and iOS to create a list. Data controls don’t exist, and the iOS solution is more code-centric than the declarative solution preferred in Oracle’s products.

However, the Oracle Mobile Cloud Service iOS SDK will again reduce the code burden for iOS developers in the following steps:

  1. Open the StorageViewController.swift file.
  2. Locate the // <<MCS CODE #02>> comment annotation, and add the following code below it to create an empty array, which will be used to hold a reference to the collection’s objects returned from the Oracle Mobile Cloud Service storage API:
    var mcsLocalCollection: [OMCStorageObject] = []
  3. Next locate the viewDidLoad() method and the // <<MCS CODE #03>> comment annotation, and below them add the following code block:
    let mcsMbeManager: OMCMobileBackendManager = 
    OMCMobileBackendManager.sharedManager()
    let mcsMbe: OMCMobileBackend = mcsMbeManager.defaultMobileBackend
    let mcsStorage: OMCStorage = mcsMbe.storage()
    let mcsRemoteCollection: OMCStorageCollection = mcsStorage
    .getCollection("OraMagSharedCollection")
    mcsLocalCollection = mcsRemoteCollection.get(0, withLimit: 9999, 
    getAllObjects: true) as AnyObject as! [OMCStorageObject]

The viewDidLoad() method is called when the page is ready to be displayed. In this code block, you can see the now familiar first two lines of code that retrieve the default mobile back end configured in the OMC.plist file at runtime.

The third and fourth code lines provide a handle on the remote storage API and the OraMagSharedCollection, which you explicitly reference in a call to getCollection(). The final code line returns an array of OMCStorageObject objects, where the get() method in this case has been configured to return all objects (from 0 to 9999), regardless of the collection’s size. For demonstration purposes, this is fine, but if your collection has thousands of objects, you can use the get() function’s parameters to paginate through the results instead, protecting the limited and valuable memory of your mobile device.

Populating the Table View with the Collection

Now that you have retrieved the Oracle Mobile Cloud Service collection and its objects, the iOS table view requires you to update the corresponding table view code in StorageViewController to retrieve and display the objects from the mcsLocalCollection array you created in the class earlier:

  1. In the tableView(numberOfRowsSelection:) function under the // <<MCS CODE #04>> comment annotation, replace the return 0 statement with the following line, which returns the total number of objects in mcsLocalCollection to display in the table view:
    return self.mcsLocalCollection.count
  2. In the tableView(cellForRowAtIndexPath:) function under the // <<MCS CODE #05>> comment annotation, add the following line of code to output the current mcsLocalCollection item’s ID for each label rendered in the cells of the table view (for example, joesSharedJsonFile.json):
    cell.textLabel?.text = self.mcsLocalCollection[indexPath.row].ID
Show the Selected Object’s Contents

At this point, the storage page will show the list of object IDs from mcsLocalCollection or any other values you want to display, which includes items in the actual object’s payload. For demonstration and learning purposes, it would be nice to show the actual contents of each object retrieved from the storage API by the previous calls. To do this, the sample app includes code to include a swipable action on each cell of the table view via tableView(editActionsForRowAtIndexPath:), where you can add logic to display the selected cell’s mcsLocalCollection object content in an alert.

  1. Within the tableView(editActionsForRowAtIndexPath:) function, locate the // <<MCS CODE #06>> comment annotation and add the following lines of code to access the selected storage object and its content type as one of the accessible properties for all storage objects:
    let mcsObject: OMCStorageObject = self
    .mcsLocalCollection[indexPath.row]
    let contentType: String = mcsObject.contentType

Next, you need to determine the best method for showing the object’s contents based on the content type. For demonstration purposes, you’ll stick to showing application/json files as a string, but you can add logic to handle other content types as you see fit. Replace the dummy if 1 == 2 statement with if contentType == "application/json"

  1. At // <<MCS CODE #07>> modify the following code to set the title and message to instead retrieve the object ID and its payload:
    let title: String = mcsObject.ID
    let message: String = String(data: mcsObject.getPayloadData(), 
    encoding: NSUTF8StringEncoding)!

In this code, the title and message display in an alert invoked via the swipable action on the selected cell in the table view.

Logout

The storage page includes a Logout button in the top toolbar that is wired to the doLogout() method in the Storage View Controller. As a final task, when the Logout button is tapped, you want to execute code to explicitly log out of Oracle Mobile Cloud Service and return to the login page.

  1. Locate the doLogout() method and the // <<MCS CODE #08>> comment annotation, and add the following code to retrieve the mobile back end and execute an explicit logout call. Replace the dummy if 1 == 1 statement with if logoutErorr == nil:
    let mcsMbeManager: OMCMobileBackendManager = 
    OMCMobileBackendManager.sharedManager()
    let mcsMbe: OMCMobileBackend = mcsMbeManager.defaultMobileBackend
    let mcsAuthorization: OMCAuthorization = mcsMbe.authorization
    let logoutError: NSError! = mcsAuthorization.logout()
    if logoutError == nil {

The application is complete, and you are free to run and test it in iOS Simulator, logging in as one of the valid users, joedoe or janeroe. The OMC.plist logLevel debug setting means that the SDK will actively log in to the Xcode debug console so you can watch what happens behind the scenes while the app communicates with Oracle Mobile Cloud Service. If you think you made a mistake, you can download and run the completed source code for this article, although you will still need to modify the OMC.plist file for your Oracle Mobile Cloud Service mobile back-end settings before running the app.

Conclusion

With the Oracle Mobile Cloud Service native SDK and the services provided by Oracle Mobile Cloud Service—such as the storage API, mobile user management services, data offline sync API, and more—you can reduce the size and complexity of the mobile apps you develop. In this article, you saw how easy it is to configure the SDK in Xcode, log users in and out, and retrieve objects from the Oracle Mobile Cloud Service storage API. The simplicity of the native SDKs and Oracle Mobile Cloud Service give mobile developers more time to focus on creating compelling mobile applications, which is essential in the mobile world, where users have very high expectations of apps, their usability, and their functionality.

Next Steps

 TRY Oracle Mobile Cloud Service.

 READ more about Oracle Mobile Cloud Service.

 WATCH Oracle Mobile Cloud Service YouTube training.

 JOIN the Oracle Mobile Platform Google+ community.

 DOWNLOAD the starter application for this article.

 DOWNLOAD the finished application for this article.

 

Photography by Raw Pixel, Unsplash