Search…
Cortex iOS

About the SDK

Welcome to the iOS Client SDK for Medable. This framework provides a wrapper for the Medable API as well as several helper tools to directly integrate those features to your iOS application.
For basic integration and initialization steps, check the README.md file in the SDK repository.

Examples

Check out the Code Samples for a few examples on how to get some specific things done with the Medable SDK. 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.

Create your Swift Project

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"

Install Medable Cortex iOS SDK

Integrate the SDK following the integration instructions from the README.md file in the SDK repository.

Initialize Medable

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 consoleSwift
1
//AppDelegate.swift
2
3
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
4
5
Medable.start()
6
Medable.client().loggerLevel = MDAPIClientNetworkLoggerLevelDebug
7
8
return true
9
}
Copied!
Then build and run the app
The app shows a blank screen but you should see proper console outputs

Integration Complete

You've successfully connected to your Medable HIPAA compliant backend. You're ready to collect PHI.

Pagination Helpers

When working with lists, it is often important to page through results. The recommended approaches to working with lists through the API are outlined here.
However, the Cortex iOS SDK makes this quite simple with pagination helpers.
The following examples illustrate how to paginate through a list of c_prescription instances.
For information on how to create custom cortex objects such as the example c_prescription object, see Data Model Setup.
For more information on working with your Cortex Objects in iOS, see Cortex Objects.

1. Using the Pagination Helper

This is how an instance of MDPaginationHelper is created and initialized:
Objective-C
1
MDPaginationHelper *prescriptions = [MDPaginationHelper
2
paginatorWithContext:@"c_prescriptions"
3
pageSize:10
4
cacheResults:NO
5
inverseOrder:NO];
6
7
// Optionally, custom API parameters (query parameters) can be specified; and the paginator will include those in the queries as well.
8
prescriptions.customParameters = [MDAPIParameterFactory parametersWithWhere:@{ @"c_refills": { @"$gt": 5 } } prefixPath:nil];
9
10
// set your class as the paginator's delegate if you use the delegate approach (see explanation below):
11
prescriptions.delegate = self;
12
13
// set the paginator's results callback block, if you use the callback block approach (see explanation below):
14
prescriptions.resultsCallback = ^(NSArray<MDObjectInstance *> * _Nullable objects, NSNumber * _Nullable hasMore, MDFault * _Nullable fault)
15
{
16
if (fault)
17
{
18
// fault handling
19
}
20
else
21
{
22
// "objects" will be instances of the Prescription class.
23
24
// Use hasMore.boolValue to know if there are more pages to load
25
}
26
};
27
28
// And then you can call either `loadNextPage` or `loadAllPages` on the paginator, depending on what you need:
29
[prescriptions loadNextPage];
30
31
// or
32
[prescriptions loadAllPages];
33
34
// ----
35
// Note: make sure to store the instance somewhere, otherwise it will be destroyed by ARC.
Copied!
If you use the delegate approach, don't forget to conform to the MDPaginationHelperDelegate protocol,
Objective-C
1
// YourClassHandlingPaginationResults.h
2
3
@interface YourClassHandlingPaginationResults <MDPaginationHelperDelegate>
4
...
5
@end
Copied!
and implement the delegate methods to get the results:
Objective-C
1
// YourClassHandlingPaginationResults.m
2
3
@implementation YourClassHandlingPaginationResults
4
5
...
6
7
- (void)paginator:(MDPaginationHelper *)paginator didLoadResults:(nullable NSArray<MDObjectInstance*> *)objects hasMore:(nullable NSNumber *)hasMore fault:(nullable MDFault *)fault
8
{
9
// handle your page results here
10
if (fault)
11
{
12
// fault handling
13
}
14
else
15
{
16
// "objects" will be instances of the Prescription class.
17
18
// Use hasMore.boolValue to know if there are more pages to load
19
}
20
}
21
22
- (void)paginator:(MDPaginationHelper *)paginator didLoadAllResults:(nullable NSArray<MDObjectInstance*> *)objects fault:(nullable MDFault *)fault
23
{
24
// handle "all the pages" results here
25
if (fault)
26
{
27
// fault handling
28
}
29
else
30
{
31
// "objects" will be instances of the Prescription class.
32
}
33
}
34
35
...
36
37
@end
Copied!
Both delegate methods are marked as optional. If you don't implement the didLoadAllResults, and loadAllPages is called, you'll get all the results in the first method, together with the results from calling loadNextPage. So, if you need to get the results of both calls separately, implement both.

📘Note

The delegate approach and the results callback approach can be used simultaneously.

📘Note

You'll find documentation about cacheResults and inverseOrder, as well as for some other pagination options (e.g. list property pagination, or paging using a field other than _id), in the MDPaginationHelper.h header file.

2. Using the Pagination Manager

If you don't want to manage the instances of MDPaginationHelper, you can leave that to the MDPaginationManager. Just create the instances using the MDPaginationManager class. Let's achieve the same as before; the only difference relies in how you create the instance:
Objective-C
1
// With this identifier, you can retrieve the instance from the MDPaginationManager later...
2
NSString *identifier = @"someIdentifier";
3
4
MDPaginationHelper *prescriptions = [MDPaginationManager
5
paginatorWithIdentifier:identifier
6
context:@"c_prescriptions"
7
pageSize:10
8
cacheResults:NO
9
inverseOrder:NO];
10
11
// the rest is the same, and you don't have to take care of storing the paginator
Copied!
Later on, that paginator's instance can be retrieved by doing this:
Objective-C
1
MDPaginationHelper *prescriptions = [[MDPaginationManager sharedInstance] paginatorWithIdentifier:@"someIdentifier"];
Copied!
If you don't need to retrieve the pagination helpers by identifier, but you still want the manager to take care of storing them; there is a function to generate random identifiers:
Objective-C
1
NSString *randomIdentifier = [MDPaginationManager randomId];
Copied!

Code Samples

Login

Objective-C
1
[[Medable client]
2
loginWithEmail:@"your email here"
3
password:@"your password here"
4
verificationToken:nil
5
singleUse:NO
6
callback:^(MDAccount * _Nullable localUser, MDFault * _Nullable fault)
7
{
8
if (fault)
9
{
10
// handle fault
11
}
12
}];
Copied!

Logout

Objective-C
1
[[Medable client] logout:^(MDFault * _Nullable fault)
2
{
3
if (fault)
4
{
5
// handle fault
6
}
7
}];
Copied!

Register User

Objective-C
1
[[Medable client]
2
registerAccountWithFirstName:@"Charles"
3
lastName:@"Best"
5
mobile:@"1-650-555-5555"
6
password:@"Thanks for the break, Banting!"
7
gender:@"m"
8
dob:[MDDateUtilities dateFromString:@"1899-02-27"]
9
role:nil
10
profileInfo:nil
11
thumbImage:nil
12
timeZone:nil
13
customPropValues:nil
14
callback:^(MDAccount* account, MDFault *fault)
15
{
16
if ( fault != nil)
17
{
18
// Handle the error (e.g. show alert with fault.message)
19
}
20
else
21
{
22
// Check whether activation is required before authentication
23
BOOL requiresActivation = [account activationRequired] ? [[account activationRequired] boolValue] : NO;
24
25
// Handle the case when requiresActivation == YES here
26
}
27
}];
Copied!

Create Object

Let's suppose we are using a custom Prescription object definition that was created using the Data Model Setup guide.
Now, we want to create instances of those objects using Cortex from the client side. Objective-C
1
NSDictionary *prescriptionBody = @{
2
@"c_date": [NSDate new],
3
@"c_dispense": @3,
4
@"c_patient": @"some patient Id reference",
5
@"c_provider": @"some provider Id reference",
6
@"c_refills": @2,
7
@"c_rx": @"Prescription details"
8
};
9
10
[[Medable client]
11
createObjectWithContext:@"c_prescription"
12
body:prescriptionBody
13
callback:^(MDObjectInstance * _Nullable instance, MDFault * _Nullable fault)
14
{
15
if (fault)
16
{
17
// handle fault
18
}
19
else if (instance)
20
{
21
// newly created instance
22
}
23
}];
Copied!

Edit Object

Let's suppose we are using a custom Prescription object definition that was created using the Data Model Setup guide.
Now, we want to edit an existing instance of that type of object using Cortex from the client side. Objective-C
1
NSDictionary *propertiesToUpdate = @{
2
@"c_dispense": @7,
3
@"c_refills": @9,
4
@"c_rx": @"Updated prescription details"
5
};
6
7
[[Medable client]
8
updateObjectWithContext:@"c_prescription"
9
objectId:[MDObjectId objectIdWithString:@"the object's Id"]
10
body:propertiesToUpdate
11
callback:^(MDObjectInstance * _Nullable instance, MDFault * _Nullable fault)
12
{
13
if (fault)
14
{
15
// handle fault
16
}
17
else if (instance)
18
{
19
// edited instance
20
}
21
}];
Copied!

List Objects

Let's suppose we are using a custom Prescription object definition that was created using the Data Model Setup guide.
Now, we want to list existing instances of that type of object using Cortex from the client side.

📘Note

For paginated listing take a look the Pagination Helpers guide.
Objective-C
1
[[Medable client]
2
listObjectsWithContext:@"c_prescription"
3
parameters:nil
4
callback:^(NSArray<MDObjectInstance *> * _Nullable objects, NSNumber * _Nullable hasMore, MDFault * _Nullable fault)
5
{
6
if (fault)
7
{
8
// handle fault
9
}
10
else
11
{
12
// hasMore is true if there are more objects to load --there's a limit in the amount of returned objects.
13
// objects contains the returned object instances
14
}
15
}];
Copied!

📘Note

If you need to use a custom class instead of MDObjectInstance and want Cortex to return instances of your class instead, follow the Cortex Objects guide.

Delete Object

Objective-C
1
[[Medable client]
2
deleteObjectWithContext:@"c_prescription"
3
objectId:[MDObjectId objectIdWithString:@"the object's Id"]
4
reason:nil
5
callback:^(MDFault * _Nullable fault)
6
{
7
if (fault)
8
{
9
// handle fault
10
}
11
}];
Copied!

File Download

Files can be downloaded using one of two methods.
Using a download path: Objective-C
1
NSString *filePath = [MDAPIClient routeWithComponents:@[ @"path", @"to", @"file" ]];
2
3
[MDAPIClient
4
downloadFileAtPath:filePath
5
callback:^(id _Nullable streamData, MDFault * _Nullable fault)
6
{
7
if (fault)
8
{
9
// handle fault
10
}
11
else if ([streamData isKindOfClass:[UIImage class]])
12
{
13
// downloaded file is an instance of UIImage
14
}
15
else if ([streamData isKindOfClass:[NSData class]])
16
{
17
// downloaded file is an instance of NSData
18
}
19
}];
Copied!
Or using a MDFacet of the File. Objective-C
1
MDFacet *aFileFacet = ...;
2
3
[aFileFacet fileDataWithCallback:^(NSData * _Nullable data, MDDataSource source, MDFault * _Nullable fault)
4
{
5
if (fault)
6
{
7
// handle fault
8
}
9
else if ([data isKindOfClass:[UIImage class]])
10
{
11
// downloaded file is an instance of UIImage
12
}
13
else if ([data isKindOfClass:[NSData class]])
14
{
15
// downloaded file is an instance of NSData
16
17
// Use source to query the source of the data
18
switch (source)
19
{
20
case MDDataSourceCache:
21
// data comes from local cache
22
break;
23
case MDDataSourceRemote:
24
// data was just downloaded
25
break;
26
default:
27
//
28
break;
29
}
30
}
31
}];
Copied!

File Upload

File uploads are a two step process as described in the File Uploads documentation.
    1.
    In the first step, a file property name and the file name is sent to the server. This could happen when creating an object and also when editing an object.
    2.
    In the response of the first step, that is, in the callback of whichever method was used in step 1 --create or update; is when the actual file upload takes place using upload information sent by the Cortex API.
For this sample, let's suppose we are creating an instance of a c_anObject object type that, has a c_image File property. We want to upload an image to the content facet of that File. Objective-C
1
// STEP 1 - Create/Update the object and send a file property key/value pairs
2
UIImage *fileToUpload = ...;
3
// Note: fileToUpload can be an instance of NSData too.
4
5
// File values are always key = facet name, value = file name.
6
NSDictionary *filePropValue = @{ @"content": fileToUpload };
7
8
// --- Optinally the mime type can be set:
9
NSDictionary *filePropValue = @{ @"content": @{ @"mime": @"image/png", @"data": fileToUpload }};
10
// ---
11
12
// Create/Update bodies are always key = prop name, value = prop value or the right type.
13
NSDictionary *createBody = @{
14
@"c_aPropName": @"aPropValue",
15
@"c_image": filePropValue,
16
@"c_someOtherPropName": @55
17
};
18
19
[[Medable client]
20
createObjectWithContext:@"c_anObject"
21
body:createBody
22
callback:^(MDObjectInstance * _Nullable instance, MDFault * _Nullable fault)
23
{
24
if (fault)
25
{
26
// handle fault
27
}
28
else if (instance)
29
{
30
// STEP 2 - File Upload - Performed internally by Cortex. Read "Managing File Uploads" to know how to keep track of file uploads. Files are also cached and encrypted locally by Cortex.
31
}
32
}];
Copied!

📘File Uploads

For a deeper management of file uploads take a look at the Managing File Uploads documentation.

Managing File Uploads

The Medable Cortex iOS SDK features an upload operations manager, that takes care of the following tasks:
    Keep an up to date list of ongoing upload operations.
    Keep an up to date list of recently successfully completed operations.
    Keep an up to date list of recently failed operations.
    Keep a progress value (percentage expressed in the 0..1 range) for each operation.
    Emit notifications for every change in the manager: - Newly added upload. - Upload completed or failed. - Upload operation progress changed.

Notifications

Every time there is a significant event in the upload operations manager, it emits a notification using the string kOperationProgressChangedNotification, which is declared in MDUploadOperations.h: Objective-C
1
/**
2
* String used to notify that an upload operation has changed its state.
3
*
4
* This can happen when the upload operation is started, its progress has changed
5
* or when it completes.
6
*/
7
extern NSString *const kOperationProgressChangedNotification;
Copied!
As expressed in the comment, this notification is emitted for every change in the upload operations manager.
How to listen the notifications: Objective-C
1
[[NSNotificationCenter defaultCenter]
2
addObserver:self
3
selector:@selector(handleUploadNotification:)
4
name:kOperationProgressChangedNotification
5
object:nil];
Copied!
How to handle the notifications: Objective-C
1
- (void)handleUploadNotification:(NSNotification *)notification
2
{
3
if ([notification.object isKindOfClass:[MDUploadOperation class]])
4
{
5
MDUploadOperation *uploadOperation = (MDUploadOperation *)notification.object;
6
7
NSString *fileName = uploadOperation.fileName;
8
NSNumber *progress = uploadOperation.progressNumber;
9
10
NSLog(@"Uploading file: %@ Progress: %f", fileName, progress.floatValue);
11
}
12
else if ([notification.object isKindOfClass:[MDUploadOperations class]])
13
{
14
// Ongoing
15
NSArray<MDUploadOperation *> *ongoingUploads = [MDUploadOperations ongoingOperations];
16
17
// Completed
18
NSArray<MDUploadOperation *> *completedUploads = [MDUploadOperations completedOperations];
19
20
// Failed - these can be retried while the upload token is still valid. Upload tokens have an expiry date.
21
NSArray<MDUploadOperation *> *failedUploads = [MDUploadOperations failedOperations];
22
}
23
}
Copied!
Within the notification, depending on the event, two different objects could be sent:
    A MDUploadOperation object is delivered inside the NSNotification.object property if it is notifying about upload progress. See below for more info.
    A MDUploadOperations object is delivered inside the NSNotification.object property if it is notifying about the following events:
      A new MDUploadOperation was added to the queue.
      A MDUploadOperation succeeded.
      A MDUploadOperation failed.
      A MDUploadOperation was removed from completed/failed.
      Flushing operations. Flushing ongoing, succeeded and failed queues.

State

The state of all upload operations can be queried from the MDUploadOperations class by checking the the following class methods: Objective-C
1
+ (NSArray<MDUploadOperation *> *)ongoingOperations;
2
3
+ (NSArray<MDUploadOperation *> *)completedOperations;
4
5
+ (NSArray<MDUploadOperation *> *)failedOperations;
Copied!
An ongoing operation is an upload task that is still uploading, i.e. it hasn't failed and it hasn't completed the upload yet.
Recently completed operations are short lived. After completion, the operation objects will stay in this list for at least 10 seconds. After this time, they'll be removed from the list.
Recently failed operations live a little longer. After failing, the operation objects will stay in this list for at least 1 minute. Again, after this time, they are be removed from the list.
Each operation is an instance of class MDUploadOperation. Here are some interesting features they provide:
    Progress: Use the progressNumber attribute to determine the progress percentage (measured in the 0..1 range) of the upload operation.
    Data Task: Use the operation property, of class NSURLSessionDataTask for the data task that the operation is using. You may call cancel on this object to cancel the upload.
    File Name: If you are uploading several things at once, the fileName property contains the name of the file being uploaded.
    NSProgress: Apple's NSProgress class allows for fine grain progress reporting, the operationProgress property returns the associated NSProgress object with this upload operations.

Cancel an Ongoing Operation

To cancel an ongoing operation, just call cancel on its data task, which you get from calling operation on the MDUploadOperation instance.
Here is code to cancel an ongoing operation: Objective-C
1
MDUploadOperation *uploadOperation = [[MDUploadOperations ongoingOperations] firstObject];
2
[uploadOperation.operation cancel];
Copied!

Retry a Failed Operation

Any operation that has failed can be retried, it need not be in the failed operations set, but beware that the upload tokens used will eventually expire.
Here is code to retry an operation currently in the failed set: Objective-C
1
MDUploadOperation *failedUploadOperation = [[MDUploadOperations failedOperations] firstObject];
2
[MDUploadOperations retryOperation:uploadOperation];
Copied!

Migration Guide

If you're upgrading from a previous version to 1.10 or newer, you will need to make the following changes:
    Remove the Medable framework from the Xcode project.
    Following the installation guide, update to the latest version.
    Replace any instance of Medable/Medable.h with MedableCortex/MedableCortex.h
Last modified 1mo ago