Get started with Swift
iOS SDK for Medable provides a wrapper for the Medable RESTful API as well as several helper tools to directly integrate those features to your iOS application.
The Medable iOS SDK is targeted to be used in apps that have a base SDK of iOS 7+ and the following instructions are targeted for Xcode 6+ users. Please consider updating if you have an older version.
To see the github repo for the Medable iOS SDK, click here.
The following articles how to get started quickly with Medable using Swift 3 and Xcode 8.
This tutorial shows one way to quickly get started using a new or existing Swift iOS project. Before you begin, you should have generated an API key. If not, do this first.
In Xcode, select
File > New Project...

Select
Single View Application
and click next.
Enter your project details. For this tutorial, we'll call the app "NewHealthCo"
Integrate the SDK following the integration instructions from the README.md file in the SDK repository.
Add the Medable start function to your AppDelegate and set the logger level to Debug so you can see more detailed network responses in the console.
Swift
//AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Medable.start()
Medable.client().loggerLevel = MDAPIClientNetworkLoggerLevelDebug
return true
}
Then build and run the app
The app shows a blank screen but you should see proper console outputs

You've successfully connected to your Medable HIPAA compliant backend. You're ready to collect PHI.
This tutorial will make use of the Account Registration route which is disabled by default in your Organization Settings. You'll want to enable registration under
Settings > Organization
in order for it to work. See Configuring Org Settings for more details.Account registration boils down to one function
Medable.client().registerAccount...
This function takes in a number of default parameters to initialize the Account object with. But only five of them are required
- First Name
- Last Name
- Email
- Password
- Mobile Number
Optional parameters include gender, dob, profile image, and role.
Here, we'll show you how to create a basic registration form using Swift and Interface Builder. At the end we provide a zip file containing the final result of this step-by-step tutorial.
- 1.Open Interface Builder (IB) by opening
Main.storyboard
- 2.Drag a Navigation Controller into IB and set it as the initial view
- 3.Set the table view Content setting to Static Cells
- 4.Drag a UITextField into a static cell with proper struts and springs
- 5.Replicate this static cell for each field you'd like to collect in this form
- 6.Associate an IBOutlet for each text field
- 7.Drag a UIBarButtonItem into the top bar and call it "Submit"
- 8.Associate an IBAction called "submitPressed" with the "Submit" button


Build and Run to make sure that you can see the form and all its placeholder values.
Add one function to the
submitPressed
function to make the form create a user in your database.Medable.client().registerAccountWithFirstName(firstNameField.text!, lastName: lastNameField.text!, email: emailAddressField.text!, mobile: "1\(mobileNumberField.text!)", password: passwordField.text!, gender: nil, dob: nil, role: nil, profileInfo: nil, thumbImage: nil, customPropValues: nil) { (account:MDAccount?, error:MDFault?) in
print("Callback returns account: \(account)")
print("Callback returns error: \(error)")
}
This function simply passes in all data entered into the form as parameters for the registration function. As an example, let's suppose we input the following into our simulator:

Submit the registration form and let's see what we get in the console:
Callback returns error: Optional(kValidationError - validation - Validation error - *Subfault: kInvalidArgument - error - Invalid Argument - The chosen password does not meet the minimum Org password strength requirement. - path: password)
We got a validation error because our password strength isn't high enough.
You set the minimum password strength in your org settings. The default minimum isGood
, which which maps to 2 on the 0-4 on the zxcvbn scale. We strongly advise against lowering this minimum.

It would be fantastic if we could immediately know whether a password will be strong enough before making an API call. Luckily, there's an open-source library that allows us to do just that.
pod 'zxcvbn-ios'
- 1.Add the zxcvbn-ios pod to your Podfile
- 2.Install dependencies by running
pod install
on your terminal - 3.Open
RegistrationTableViewController.swift
andimport zxcvbn_ios
at the top - 4.Make
RegistrationTableViewController
a delegate for the password text field - 5.Drag a UIView next to the UITextField for the password
- 6.Set this UIView to a Custom Class called DBPasswordStrengthMeterView and drag as an IBOutlet into the controller

The final step is to implement the UITextField Delegate function so that each change in the password field is given a new strength indicator
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let password = (textField.text! as NSString).replacingCharacters(in: range, with: string)
passwordStrengthMeter.scorePassword(password)
return true
}
Build and Run
I've turned off secure text entry to show that the meter does indeed adjust to the complexity of the password

We want to be sure that when we submit the form, the password strength is at least as strong as our org setting minimum. The default minimum is 2 (Good). The lowest is 0 (Weakest). Add the following lines to the
submitPressed
function before calling register.if DBZxcvbn().passwordStrength(passwordField.text!).score < 2 {
print("The password is not strong enough")
return
}
Now our password validation happens locally before making any network calls and our user isn't left guessing a million different passwords hoping they'd meet the minimum strength requirement!
Another type of error you might get when trying to call register is kInvalidPhoneNumberFormat. This means the entered mobile number is probably not a real number. Medable uses Google's phonelib to validate numbers.
Let's use the iOS version of phonelib to check that a number is valid before making an API call
pod 'libPhoneNumber-iOS'
- 1.Add the libPhoneNumber-iOS pod into your Podfile and
pod install
in the terminal - 2.Open
RegistrationTableViewController.swift
andimport libPhoneNumber_iOS
at the top - 3.Add the following lines to the
submitPressed
function before calling register.let phoneUtil = NBPhoneNumberUtil() do { let myNumber = try phoneUtil.parse(mobileNumberField.text!, defaultRegion: "US") if !phoneUtil.isValidNumber(myNumber) { return } } catch let error as NSError { print(error) }
We first define the util that will parse and validate the user's mobile number. To test this, run the app with an obviously invalid phone number like 12223334444 and the function should return with an error in the console without calling register.
Note: the mobile number must be formatted with the country code included or it will be marked as invalid and registration will fail.
You now have a registration form to sign up new users!
We've finished Registration and now it's time to allow registered users to log back in. First, add screens to the IB for login.

Link the form fields and submit button actions just as we did for the registration view

Logging in is done through the function
.authenticateSessionWithEmail...
which takes in 4 parameters- 1.Email
- 2.Password
- 3.Verification Token - this is an optional parameter that you only set when the user is using 2fa to verify his/her identity
- 4.Single Use - having this set to
false
tells the Medable SDK to remember the current device for all future login attempts so that 2fa is no longer required for this specific account on this specific device
If you attempt to login on the same iOS simulator or device that you used for registration, the authentication should succeed without a verification token.Swift
Medable.client().authenticateSession(withEmail: emailAddressField.text!, password: passwordField.text!, verificationToken: nil, singleUse: false) { (account:MDAccount?, error:MDFault?) in
print("Callback returns account: \(account)")
print("Callback returns error: \(error)")
}
Attempting to authenticate a user results in three common scenarios
Callback returns account: Optional(Id: 5784279b46b010416570d2ac Name: John Smith eMail: [email protected])
To test this you simply register an account on one simulator/device and try to login to that same account on a different version simulator or different device. Alternatively, you could delete the app between registration and installation.
Callback returns error: Optional(kNewLocation - location - A new location has been added to the account. Please verify it -)
Or, if the user was already sent a verification code but still tries to login without passing in a verification code
Callback returns error: Optional(kUnverifiedLocation - location - Access by this location is pending account holder verification -)
So if the callback returns either of these error messages, we prompt the user to enter the 6-digit verification code that Medable automatically sends to the mobile number associated with the account (via SMS).
Create an instance of
UIAlertController
to collect this information and call authorize again with the code passed in as a parameter (instead of nil)if let code = error?.code {
if code == kMDAPIErrorNewLocation || code == kMDAPIErrorUnverifiedLocation {
self.present(self.verificationCodeController, animated: true, completion: nil)
}
}

For security reasons, the Medable API will never indicate whether the email doesn't exist in the database or the password was incorrect for an existing email.
Instead the API simply accepts or denies a given combination of email/password.
Callback returns error: Optional(kInvalidCredentials - auth - Invalid email/password combination -)
Add a "Reset Password" button to the tab bar and corresponding IBAction
@IBAction func passwordResetPressed(_ sender: UIBarButtonItem) {
self.present(self.passwordResetController, animated: true, completion: nil)
}
When the button is pressed, we present a
UIAlertController
once again to collect the email address that the user is trying to login with.

Here's the setup code for the two UIAlertController.
Swift
var verificationCodeController = UIAlertController(title: "Verification Code", message: "Enter the 6-digit code that was sent to your mobile device", preferredStyle: .alert)
var passwordResetController = UIAlertController(title: "Password Reset", message: "Enter the email address you used to register and we'll email you a password reset link.", preferredStyle: .alert)
override func viewDidLoad() {
super.viewDidLoad()
verificationCodeController.addTextField { (textField:UITextField) in
textField.keyboardType = .numberPad
}
verificationCodeController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
verificationCodeController.addAction(UIAlertAction(title: "Submit", style: .default, handler: { (action:UIAlertAction) in
if let verificationCode = self.verificationCodeController.textFields?.first?.text {
Medable.client().authenticateSession(withEmail: self.emailAddressField.text!, password: self.passwordField.text!, verificationToken: verificationCode, singleUse: false) { (account:MDAccount?, error:MDFault?) in
print("Callback returns account: \(account)")
print("Callback returns error: \(error)")
}
}
}))
passwordResetController.addTextField { (textField:UITextField) in
textField.keyboardType = .emailAddress
}
passwordResetController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
passwordResetController.addAction(UIAlertAction(title: "Submit", style: .default, handler: { (action:UIAlertAction) in
if let email = self.passwordResetController.textFields?.first?.text {
Medable.client().requestPasswordReset(withEmail: email, callback: { (error:MDFault) in })
}
}))
}
Once login is successful, the
Medable.client().currentUser
object is defined for you to access details regarding the logged-in user from any file in the project.In this tutorial, we'll demo the built-in push notification feature of Medable. The setup involves a 4-step configuration:
- 1.Generate PEM file
- 2.Enable Medable Push Notifications
- 3.Send Medable Push
- 4.Xcode Setup
Start by navigating to developer.apple.com
Go to "Certificates, Identifiers & Profiles" -> "Identifiers" -> "App IDs"
Select your app ID -> Click
Edit
-> Enable Push Notifications
-> Under Development SSL Certificate
, Click Create Certificate
Follow Apple's instructions to create a certificate named
Apple Development IOS Push Services: APP ID HERE
in your Keychain Access appRight click on this certificate and select the
export
option.

Name it something like
MedableDevPushCertificate
-> Change format to .p12
-> Click SaveIf you don't see the .p12 option in the dropdown, navigate to the "Certificates" section in the left navigation and right click on the certificate from there

It will prompt you to enter a password - DO NOT enter any password - simply click OK with the fields empty

Open Terminal -> cd into the folder that contains
MedableDevPushCertificate.p12
-> copy paste the following command $ openssl pkcs12 -in MedableDevPushCertificate.p12 -out MedableDevPushCertificate.pem -nodes -clcerts
🚧IMPORTANTDO NOT enter a password when prompted after issuing the above command in the terminal - just press enter to continue
Open MedableDevPushCertificate.pem in the text editor of your choice, from the Terminal or Finder
You should see a bunch of mumbo jumbo clearly delineated by
-----BEGIN CERTIFICATE-----
and -----END CERTIFICATE-----
and -----BEGIN RSA PRIVATE KEY-----
and -----END RSA PRIVATE KEY-----
Congrats! Part 1 is done. But keep this .pem file open - we'll be copy pasting some of this into your Medable App Settings
If you're having trouble getting to this point, there's a more detailed guide here if you scroll down to "Creating an SSL Certificate and PEM file"
- 1.Go to your Medable Admin Portal- app.dev.medable.com/
- 2.Settings => Apps => Select your app
- 3.Check
APNs Debug Gateway Option
- only do this if you're inputting a development certificate. - 4.Copy everything from begin certificate to end certificate (including markers) into the
APNs Certificate
field - 5.Copy everything from begin RSA private key to end RSA private key (including markers) into the
APNs Private Key
field
Remember that in this example, we'll be sending a push notification once a user logs in successfully. Create a trigger script to achieve this behavior.
Create a custom notification by going to Settings -> Notifications -> Custom Notifications -> New Notification

Click
Add Endpoint
