Skip to content

Getting Started

Arpillai edited this page Nov 8, 2017 · 26 revisions

PredixSDKForiOS Getting Started

The Predix SDK for iOS is the easiest way to integrate with Predix services. As of now it provides

  • Timeseries API
  • Authentication (UAA) API
  • Asset API
  • UI Component
  • A Local NoSQL Database
  • Online API
  • Offline/Data sync

Create a New Project

Open XCode and create a Single View App Xcode

File > New > Project > iOS > Single View App

Install and Configure the PredixSDKForiOS

You can choose to install the SDK using Carthage or by downloading the binary from our GitHub repository.

Using Carthage

     1. If you haven’t already, install the latest version of Carthage
     2. Create a file named `cartfile`
     3. Enter PredixMobileSDK framework location —>   `binary "https://raw.githubusercontent.com/PredixDev/PredixMobileSDK/master/Carthage/ios.json" ~> 3.8`
     4. Run `carthage update`
     5. `PredixMobileSDK.framework` is available at ./Carthage/Build/iOS.

Downloading Binary

​ Download the latest PredixSDKForiOS framework from https://github.com/PredixDev/PredixSDKForiOS/releases

Add SDK to Project

  1. Open your application's Xcode project.

  2. Create a Frameworks group in your project.

  3. Open downloaded framework using finder ( typically in ~/Downloads/PredixMobileSDK_iOS_vX.X.zip) or grab one from the Carthage build.

  4. Drag the PredixMobileSDK.framework into the Frameworks group of Xcode's Project Navigator.

  5. In Xcode select project/TARGETS//General tab in your project.

  6. In Embeded Binaries section add the Add PredixMobileSDK.framework from Frameworks group.

Add SDK to Project Image

Add the Module Map

PredixSDKForiOS internally utilizes CouchbaseLite for syncing with the backend and it is written in Objective-C. Xcode requires a module map file so that PredixSDKForiOS can use CouchbaseLite module.

  1. Navigate to the ViewController.swift file and add an import for PredixMobileSDK.
  2. As soon as you try to build the project CMD + B you will see the following error -> Missing required module 'CouchbaseLite

Module Map Missing Error Image

  1. To fix the above error, create a folder group called CouchbaseLite

  2. Next, create an "Empty" file in the CouchbaseLite group and name it module.modulemap (CouchbaseLite/module.modulemap)

  3. Add the following content to the module.modulemap file :

module CouchbaseLite {
    export *
}

The module.modulemap file should look like the following image:

Module Map Project

  1. Select the project and then select the non-test target under targets
  2. Select the Build Settings tab and search for import paths
  3. Find section for Swift Compiler - Search Paths and update the Import Paths value with $(SRCROOT)/$(PRODUCT_NAME) module map build settings

NOTE: If you have Show Setting Names enabled in the editor menu the Setting name of the key will be SWIFT_INCLUDE_PATH instead of Import Paths

  1. Build the project again CMD+B, compiler should be able to find the missing CouchbaseLite module by now.

The following screenshot shows how the project structure looks like after you build the project:

screen shot 2017-10-24 at 11 00 57 am

Authentication UI

Lets create the UI in Main.storyboard/ViewController which will initiate the authentication call, take credentials input, and display the ongoing activity/results.

Authentication UI Image

IBOutlets for the controls which we have just created above are named as:

@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var signInButton: UIButton!
@IBOutlet weak var statusLabel: UILabel!

IBAction functions:

@IBAction func signInPressed(_ sender: Any) {

}

Hit the run button in XCode. We should see the login button in simulator/device.

FirstRun

Authenticate with UAA

Note: This guide does not cover the instructions to set up a UAA service, for more information on UAA Service, see https://www.predix.io/services/service.html?id=1172

Note: Authentication documentation: http://predixdev.github.io/PredixMobileSDK/iOS/Classes/AuthenticationManager.html
and other examples are available at: https://github.build.ge.com/predix-mobile/iOSAuthenticationExampleApps

First we need to make our ViewController a ServiceBasedAuthenticationHandlerDelegate

import UIKit
import PredixMobileSDK

class ViewController: UIViewController, ServiceBasedAuthenticationHandlerDelegate {
   ...
}

Now we need to create a couple of class properties to hold our credential provider and authentication manager

class ViewController: UIViewController, ServiceBasedAuthenticationHandlerDelegate {
    ...
    private var credentialProvider: AuthenticationCredentialsProvider?
    private var authenticationManager: AuthenticationManager?
}

For your convenience, we have defined a function in the ViewController to handle updating the lable text on the main thread so that we don't have to deal with it in the code that matters:

class ViewController: UIViewController, ServiceBasedAuthenticationHandlerDelegate {
...

private func updateStatusText(message: String) {
    DispatchQueue.main.async {
        self.statusLabel.text = message
    }
}

Next, create an authentication configuration and an authentication manager.
In the ViewControllers 'ViewDidLoad' method, add the following code:

override func viewDidLoad() {
    super.viewDidLoad()
        
    //Creates an authentication manager configuration configured for your UAA instance.  The baseURL, clientId and clientSecret can also be defined in your info.plist if you wish but for simplicity we have added these to the config below.
    var configuration = AuthenticationManagerConfiguration()
    configuration.baseURL = URL(string: "https://predixsdkforiosdemo.predix-uaa.run.aws-usw02-pr.ice.predix.io")
    configuration.clientId = "NativeClient"
    configuration.clientSecret = "test123"

    //Create an online handler so that we can tell the authentication manager we want to authenticate online
    let onlineHandler = UAAServiceAuthenticationHandler()
    onlineHandler.authenticationServiceDelegate = self

    //Create an authentication manager with our UAA configuration, set UAA as our authorization source, set the online handler so that the manager knows we want to authenticate online
    authenticationManager = AuthenticationManager(configuration: configuration)
    authenticationManager?.authorizationHandler = UAAAuthorizationHandler()
    authenticationManager?.onlineAuthenticationHandler = onlineHandler
        
    //Tell authentication manager we are ready to authenticate, once we call authenticate it will call our delegate with the credential provider
    authenticationManager?.authenticate { status in
        self.updateStatusText(message: "Authentication \(status)")
    }
        
    self.updateStatusText(message: "Authentication Started")
}

Apply the Authentication Logic

We need to implement a few delegate methods so that our controller can react to events that happen during the authentication process.

  1. Implement the credential provider method as shown below:
func authenticationHandler(_ authenticationHandler: AuthenticationHandler, provideCredentialsWithCompletionHandler completionHandler: @escaping AuthenticationCredentialsProvider) {
    //Set our credential provider so that when we sign in we can pass the username and password from the text fields to the authentication manager
    credentialProvider = completionHandler
}
  1. Implement two additional methods that will be called in the event of an error or if the user is unable to authenticate because of entering bad credentials
public func authenticationHandler(_ authenticationHandler: PredixMobileSDK.AuthenticationHandler, didFailWithError error: Error) {
    updateStatusText(message: "Authentication failed: \(error)")
}
    
public func authenticationHandlerProvidedCredentialsWereInvalid(_ authenticationHandler: AuthenticationHandler) {
    updateStatusText(message: "Invalid username and/or password")
}

After applying all the authentication logics, lets call it from the login button IBAction. Replace the @IBAction func signInPressed(_ sender: Any) logic with following code:

@IBAction func signInPressed(_ sender: Any) {
    updateStatusText(message: "Authentication credentials received, sending request to UAA")
    //Give the username and password to the credential provider
    credentialProvider?(self.usernameTextField.text ?? "", self.passwordTextField.text ?? "")
}

Click on the run button in XCode and then click the login button, you should see a login screen similar to the following:

UAA Auth login Image

Now, when you enter valid credentials and hit login you should see the following on your screen:

Note: if you are using our example UAA instance the credentials for the username and password is: demo

UAA loggedin image

Next Steps

Congratulations! You have successfully completed the Getting Started with the PredixSDKForiOS!

You can download the complete project here

Related Documentation

For more information about authentication, see authentication guides and examples (Coming Soon!)

For any other features, see our main guide here (Coming Soon!)

If you want to check out the awesome UI framework, see the PredixUIKit guides here (Coming Soon!)