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 ReadyThis 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.
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 ServiceThe 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:
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 PageWithin 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:
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 CollectionHaving 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:
var mcsLocalCollection: [OMCStorageObject] = []
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 CollectionNow 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:
return self.mcsLocalCollection.count
cell.textLabel?.text = self.mcsLocalCollection[indexPath.row].ID
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.
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".
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.
LogoutThe 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.
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.
ConclusionWith 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.
|
Photography by Raw Pixel, Unsplash