June 7, 2016

Salesforce Mobile SDK QuickStart

By William Welbes

Swift-ly Access Salesforce data in iOS

Let's assume your organization is one of the thousands that uses Salesforce for customer relationship management. For those of us less inclined to sell widgets, but more inclined to build software to help sell those widgets... good news. Salesforce has a robust Force.com development platform.

Salesforce has released a set of REST APIs as well as mobile SDKs that can be implemented in native mobile apps to access Salesforce.com data. There are several different development options and approaches in the SDKs including hybrid apps. The focus of this article is to implement the native mobile SDK inside a Swift based iOS app.

Since Apple's release of Swift a couple years ago, the iOS development community has really embraced the new language. The open sourcing of Swift this past December has also thrown fuel on its adoption and expansion. As I approach development of new apps today, I nearly always opt to use Swift. It's a fun way to build for iOS.

So if you have a Swift based iOS app that you want to add Salesforce.com to... how do you get started?

The Salesforce Developer site has a lot of great resources, but it can be a bit daunting to jump in. My usual starting point when looking to integrate with a third party in iOS is CocoaPods. However, there is not an official pod in the searchable database. It turns out that the iOS SDK does use CocoaPods, but it's a bit more involved.

Salesforce has a set of tools and a lengthy SDK guide that walks through the process of creating a new native app that implements the SDK. However, the focus of this article is to simply add the SDK to an existing project and get up and running quickly (dare I say swiftly 😀).

Official Salesforce Mobile SDK

The official Mobile SDK for iOS is hosted on GitHub. This is ultimately where I landed for implementing this solution, but it is worth pointing out another Swift based library called SwiftlySalesforce.

SwiftlySalesforce

SwiftlySalesforce was created by Michael Epstein, a senior technical evangelist at Salesforce. It appears that the library is not the "official" path for integration. It was also just released in May of this year so it is a new kid on the block compared to the official SDK. I did a quick implementation and assessment of it, and it seems like a great option for simple integrations. It uses PromiseKit and Alamofire, two very popular libraries in the Swift community for asynchronous requests. The project is open source, but so far the only contributor is Michael. It will be interesting to see if this gains more steam within Salesforce.

Step by Step: Salesforce Mobile SDK

Here's the steps we will take to integrate with the Salesforce Mobile SDK via Swift:

  1. Create a Salesforce development account
  2. Create a Connected App in Salesforce to get an API consumer key
  3. Create a new Xcode Swift based project (or use an existing project)
  4. Integrate the Salesforce SDK via CocoaPods
  5. Connect the SDK in the AppDelegate
  6. Add Salesforce.com App Transport Security exceptions
  7. Retrieve contacts via SOQL on the RestAPI

Create a Salesforce development account

If you don't already have a Salesforce account, it is free for developers. Sign up and create your own development instance. This way you won't be creating fake leads in your live instance that your sales team starts cold calling 😀

Create a Connected App in Salesforce to get an API consumer key

Once you have a Salesforce developer account, you need to create a Connected App in Salesforce that will allow you to connect via the REST API.

  1. Log in to Salesforce.com
  2. Tap Setup at the top near your login name.
  3. Type "app" in the Quick Find menu on the left
  4. Scroll down the now filtered menu on the left side and tap the Build > Create > Apps option
  5. Scroll to the bottom of the Apps page and find the Connected Apps section.
    connected-apps
  6. Tap New to create a new Connected App
  7. Enter the basic information for the app: App Name, API Name, and a contact email.
    Create a new Salesforce Connected App
  8. Check the box to enable OAuth Settings
  9. Specify a callback URL format that your app will use after a user authenticates. This doesn't have to be a valid web address, but must be in URL format. For the ContactsForce example app, I've used: contactsforce:///oauth/done
  10. Select the appropriate OAuth permissions for your app: "Access and manage your data (api)" and "Provide Access to your data via the Web (web)" at a minimum
    Selected OAuth scopes
  11. Tap Save at the bottom of the page and you should be taken to your newly created app's detail page. The API OAuth section on this page contains the Consumer Key and Callback URL* that you will need to integrate with the SDK.

Create a new Xcode Swift based project (or use an existing project)

Ok. An easy step. Create a new Swift based iOS app project or open your existing Swift based project. I created an example app called ContactsForce that loads and displays Salesforce contacts in a simple table. The rest of the steps in this walk through make use of the ContactsForce app example.

ContactsForce Screenshot

Integrate the Salesforce SDK via CocoaPods

Add a reference to the Salesforce SDK source code for the pods in your Podfile. Here is what my Podfile looks like:

Run pod install and be sure to now open the .xcworkspace file rather than the .xcodeproj file.

Connect the SDK in the AppDelegate

In my example app, ContactsForce, I implemented the Salesforce SDK in a simple Singleton class to contain the SDK calls in a single area: SalesforceManager.

The AppDelegate class will call two methods on the SalesforceManager to setup and present authentication for Salesforce. First, setupSDKManager() is called to setup the SDK in the init method of the AppDelegate and then when the app has finished launching, launch() is called. The launch() method will check to see if Salesforce is authenticated and present a login view controller from the SDK that presents a web view allowing the user to log in.

The setup method is implemented in the SalesforceManager as shown below. It sets the connectedAppId and other parameters and then ties in some blocks for handling at different states in the launch process. Be sure to enter your Connected App Consumer Key and callback URL here so that the app can connect to your app.

The launch() method is a simple pass through to the SalesforceSDKManager’s launch call:

Add Salesforce.com App Transport Security exceptions

If you build and run your app at this point, you may encounter SSL transport security errors from iOS. You must add exceptions to the info.plist file in order to allow the app to connect to salesforce.com and force.com.

app-transport-security

Now if you build and run your app, the Salesforce SDK should pop up a view controller to allow the user to enter Salesforce.com credentials and log in.

salesforce-login

Once the user authenticates, an OAuth screen asks the user for permission for your app to access their data. Once the user allows access, the login view controller is dismissed and the SDK stores the user’s token. That token will now be used on subsequent calls to the API.

Retrieve contacts via SOQL on the RestAPI

Now that we have the SDK setup, have connected to the Salesforce.com API and have authenticated a user, let’s exercise one of the API methods and retrieve some data. The SFRestAPI defines the interface for creating and formatting Salesforce REST requests. The SFRestAPI can be implemented using the SFRestDelegate protocol or using some block based calls implemented in the SFRestAPI Blocks Category. For our case, the blocks implementation allows us to implement the response and error handling right inline where we make the calls. I’ve implemented a call to the SFRestAPI inside the SalesforceManager singleton that fetches contacts. The requestForQuery() method takes Salesforce SOQL code for selecting contacts.

The response is returned as JSON that is deserialized as a dictionary of contact data elements. I then defined a SalesforceContact class that parses the dictionary into properties that will be easy to consume else where in the app.

Lastly, in my example app, I implemented a UITableViewController subclass as the main view controller that simply calls the SalesforceManager class to load contacts and then display them in the table view.

I’ve published the example project ContactsForce out on GitHub. If you want, you can simply clone, build and run that app. NOTE: The configuration of the ConsumerKey and RedirectURL needs to be placed in the Configuration.plist file in order to connect to your Salesforce Connected App.

Always Be Closing

Hopefully you’ve swiftly completed this step by step and are ready to dive in on your own implementation. The Salesforce.com developer website has lots of resources, information and tutorials.

If you are looking for more expert help with Salesforce, Centare is a Salesforce Partner. We would be happy to talk to you about how we can help your organization build software that integrates with the Salesforce platform.

You made it to the end. Now you’re entitled to a cup of coffee. ☕️


William Welbes - Developer

About William Welbes

Will is a Solutions Architect and consultant at Centare with a passion for building great software. With over 15 years of experience in software development, he has helped clients develop solutions across many different industries.