iOS SDK

Developer Guide Mobile App Engine (iOS)

Getting Started

Step 1: Get the Mobile App Engine and an API Key from Arrayent

The Arrayent Mobile App Engine for iOS is only available to existing Arrayent customers. If you are an existing customer with a contractual agreement to use the Mobile App Engine, complete the instructions below to get your API Key and Mobile App Engine package. If you are not an existing Arrayent customer, contact sales@arrayent.com to request access.

  1. Decide on a bundle identifier. We recommend a bundle identifier that conforms to the following pattern:com.<company>.<project>.<app>
  2. Submit a customer support ticket to Arrayent. Provide your bundle identifier in the ticket. Request the following items from Arrayent:
    • Mobile App Engine for iOS
    • API Key
    • Application Name
    • Cloud URL

    See the following to learn how to submit support requests: Zendesk

If you ever change your bundle identifier you will need to submit a new customer support ticket and get a new API key from Arrayent.

Step 2: Import Mobile App Engine

  1. Drag and drop the libAppEngine.a and header files into your project.../../_images/setup-1.png../../_images/setup-2.png
  2. Under Build Settings > Linking > Other Linker Flags add -ObjC.../../_images/setup-3.png
  3. Under Build Phases > Link Binary with Libraries add libsqlite3.dylib, CoreMedia, AVFoundation, and ImageIO.
  4. Clean and build the application. You should not have any errors.../../_images/setup-4.png

API Overview

This chapter contains an overview of how to use the Arrayent Mobile App Engine API in your project. See the example application, header files, and Apple Docs contained inside of the Arrayent Mobile App Engine for more detailed examples and documentation.

Initialization

When initializing the Mobile App Engine, pass your API Key as an argument:

[AppEngine initialize:API_KEY];

Configuration

Cloud Environments

By default the Mobile App Engine points to the Arrayent DevKit cloud environment:

https://DevKit-api.arrayent.com/zdk/services/zamapi/

To point the engine to a different environment:

[[AppEngine sharedInstance] setCloudUrl:CLOUD_URL];

CLOUD_URL must be a string like the following:

``https:://<SUBDOMAIN>.arrayent.com/zdk/services/zamapi/``

Replace <SUBDOMAIN> with the subdomain of your cloud environment. Do not modify anything else in the URL.

Application Name

Set the application name if you need to use any Arrayent Web Service API v2 operations:

[[AppEngine sharedInstance] setApplicationName:APP_NAME];

Set the application name before logging in. The Mobile App Engine does not provide a default application name.

Database Caching

Setting the Mobile App Engine to demonstration mode forces the Mobile App Engine to return pre-populated data from a locally stored database file, rather than actually send web service requests to the Arrayent Cloud. The database file should be stored in the assets directory of your application. To set the Mobile App Engine to demonstration mode:

[[AppEngine sharedInstance] setDataBaseCachingMode:DataBaseCachingTypeDemo];

To set the Mobile App Engine to normal mode:

[[AppEngine sharedInstance] setDataBaseCachingMode:DataBaseCachingTypeNormal];

Object Factory

The Object Factory class provides concrete objects for all the management classes that can have multiple implementations depending on the state of the application. Never keep a local copy of any object. Always use the Object Factory for requesting objects. For example, to retrieve the account management instance:

#import "ObjectFactory.h"
[[ObjectFactory sharedInstance] getAccountManagerInstance];

Account and Session Management

Login

To log in to the Arrayent Cloud:

#import "AccountManagerProtocol.h"

id accountManager =
    [[ObjectFactory sharedInstance] getAccountManagerV2Instance];

[accountManager userLogin:USERNAME
                password:PASSWORD
                success:^(UserLoginResponse *response) {
  // User Login is successful
  NSLog(@"UserLogged In Successfully");
} failure:^(SDKError *error) {
  // Some error in logging in user.
  NSLog(@"Error");
}];

System Login

To get administartive rights for delete users, configure email templates etc:

#import "AccountManagerProtocol.h"

id accountManager =
  [[ObjectFactory sharedInstance] getAccountManagerInstance];
[accountManager systemLogin:USERNAME password:PASSWORD success:^(SystemLoginResponse *responseData) {
    //returns system security token on success
} failure:^(SDKError *error) {
    NSLog(@"Error");
}];

Logout

To log out of the Arrayent Cloud:

#import "AccountManagerProtocol.h"

id accountManager =
    [[ObjectFactory sharedInstance] getAccountManagerInstance];

[accountManager logOut:^(LogoutResponse *responseData) {
  // User logged out.
} failure:^(SDKError *error) {
  NSLog(@"Error while Signing out.");
}];

Logging out clears all session tokens from the Mobile App Engine.

Get User Account Information

To retrieve the current values for all of the user attributes for the currently logged in user:

#import "AccountManagerProtocol.h"

id accountManager =
  [[ObjectFactory sharedInstance] getAccountManagerInstance];

[accountManager getAccountById:USER_ID success:^(GetAccountResponse *response) {
  //Read Account details from response
} failure:^(SDKError *error) {
  // Some error in getting account details.
  NSLog(@"Error");
}];

Set User Account Information

To set the values of one or more user attributes:

#import "AccountManagerProtocol.h"

[accountManager updateAccountWithAttributeName:ATTRIBUTE_NAME
                andAttributeValue:UPDATED_VALUE_FOR_ATTRIBUTE
                success:^(CommonRetCodeResponse*responseData) {
    //Account details updated
} failure:^(SDKError *error) {
    // Some error in updating account details
    NSLog(@"Error");
}];

Get User Attributes

To get list of attribute names for the current user:

#import "AccountManagerProtocol.h"

id accountManager =
    [[ObjectFactory sharedInstance] getAccountManagerInstance];
[accountManager getUserAttributesList:^(UserAttributes *responseData) {
    //List of attribute names
} failure:^(SDKError *error) {
    NSLog(@"Error");
}];

Create New User

To create or register a new user:

#import "AccountManagerProtocol.h"

id accountManager =
    [[ObjectFactory sharedInstance] getAccountManagerInstance];
[accountManager registerUser:userName
                andPassword:password
                withEmail:emailAddress
                fullName:fullName
                forApplicationId:appId
                language:language
                success:^(CommonRetCodeResponse *response) {
  // New user created.
} failure:^(SDKError *error) {
  // Create user attempt failed.
}];

language defaults to En. Upon receiving this request, the Arrayent Cloud sends a activation code to the specified email. The end user must retrieve this activation code from the email and provide it to the application. The application must then call the following to send the activation code to the Arrayent Cloud:

[accountManager activateUser:ACTIVATION_CODE
                success:^(CommonRetCodeResponse *response) {
  // Activation code confirmed on cloud.
} failure:^(SDKError *error) {
  // Code is invalid, or cloud rejected.
}];

Delete User

To delete user account. Precondition – must perform system login:

#import "AccountManagerProtocol.h"

  id accountManager =
[[ObjectFactory sharedInstance] getAccountManagerInstance];

  [accountManager deleteAccountById:USER_ID success:^(CommonRetCodeResponse *responseData) {
//return code = 0 indicated success
  } failure:^(SDKError *error) {
NSLog(@"Error - %@", error.message);
  }];

Reset Password

To request a password recovery code:

#import "AccountManagerProtocol.h"

id accountManager =
    [[ObjectFactory sharedInstance] getAccountManagerInstance];
[accountManager requestPasswordRecoveryCode:EMAIL_ADDRESS
                success:^(CommonRetCodeResponse *response) {
  // Activation code sent to EMAIL_ADDRESS.
} failure:^(SDKError *error) {
  // Not sent.
}];

The end user will receive an email containing a password recovery code. The end user must provide this code to the application. The application can then reset the password with the following call:

id accountManager =
    [[ObjectFactory sharedInstance] getAccountManagerInstance];
[accountManager updatePassword:password
                forUserName:userName
                andRecoveryCode:recoveryCode
                success:^(CommonRetCodeResponse *response {
  // Password successfully reset.
} failure:^(SDKError *error) {
  // Invalid code, or other error.
}];

Device Management

Get Device Types

To retrieve all currently defined Device Types:

#import "DeviceManagerProtocol.h"

[deviceManager getDeviceTypeList:^(DeviceTypes *response) {

} failure:^(SDKError *error) {
  NSLog(@"Error - %@", error.message);
}];

Add Device

To add a device to a user’s account:

#import "DeviceManagerProtocol.h"

id deviceManager =
    [[ObjectFactory sharedInstance] getDeviceManagerInstance];
[deviceManager addDevice:DEVICE_NAME
               password:DEVICE_PASSWORD
               deviceTypeName:DEVICE_TYPE
               success:^(CommonRetCodeResponse *response) {
  NSLog(@"Device Added Successfully");
} failure:^(SDKError *error) {
  NSLog(@"Error - %@", error.message);
}];

Get Device(s)

To get the current device attribute values of a single device (as well as information about each the definition of each device attribute):

#import "DeviceManagerProtocol.h"

id deviceManager =
    [[ObjectFactory sharedInstance] getDeviceManagerInstance];
[deviceManager getDeviceById:DEVICE_ID
               typeName:DEVICE_TYPE_NAME
               success:^(DeviceAttributesList *responseData) {
  // Response is list of device attribute list
  DeviceAttributesList *list = (DeviceAttributesList*) responseData;
} failure:^(SDKError *error) {
  NSLog(@"Error %@",error.message);
}];

To get all devices owned by this user:

 [deviceManager getDevicesDetails:^(DeviceDetailsList *response) {
 //list of attributes of all devices
} failure:^(SDKError *error) {
 NSLog(@"Error %@",error.message);
}];

To get all devices owned by this user and their attributes:

 [deviceManager getDevicesDetails:^(DeviceDetailsList *response) {
    //list of attributes of all devices
} failure:^(SDKError *error) {
    NSLog(@"Error %@",error.message);
}];

Get Devices Attributes With Values Since Time

To get all device attributes which have been updated on or after a specified timestamp (in milliseconds):

#import "DeviceManagerProtocol.h"

id deviceManager =
    [[ObjectFactory sharedInstance] getDeviceManagerInstance];
[deviceManager getDeviceById:DEVICE_ID
               typeName:DEVICE_TYPE_NAME
               sinceTime:TIME_STAMP
               success:^(DeviceAttributesList *responseData) {
  // Response is list of device attribute list
  DeviceAttributesList *list = (DeviceAttributesList*) responseData;
} failure:^(SDKError *error) {
  NSLog(@"Error %@",error.message);
}];

Set sinceTime to 0 to return all attributes. When this operation is used in combination with Periodic Update, the timestamp will be automatically calculated and updated by the Arrayent engine.

Set Device

To set a device attribute (i.e. send a command to a device):

#import "DeviceManagerProtocol.h"

id deviceManager =
    [[ObjectFactory sharedInstance] getDeviceManagerInstance];
[deviceManager updateDevice:DEVICE_ID
               attributeValues:PARAMS_DICTIONARY
               success:^(CommonRetCodeResponse *response) {
  NSLog(@"Device Attribute Updated");
} failure:^(SDKError *error) {
  NSLog(@"Error while updating device attribute");
}];

Delete Device

To delete a device from a user account (so that the user can no longer monitor and control it):

#import "DeviceManagerProtocol.h"

id deviceManager =
    [[ObjectFactory sharedInstance] getDeviceManagerInstance];
[deviceManager removeDevice:DEVICE_ID success:^(CommonRetCodeResponse *response) {
  // Device deleted from Account
} failure:^(SDKError *error) {
  NSLog(@"Error while removing the device.");
}];

Get Attribute names for a device type

To get a list of attribute names for the given device type:

#import "DeviceManagerProtocol.h"

  id deviceManager =
[[ObjectFactory sharedInstance] getDeviceManagerInstance];
  [deviceManager getDeviceAttributesList:DEVICE_TYPE_NAME success:^(DeviceAttributesList *response) {
    //List of attribute names
 } failure:^(SDKError *) {
    NSLog(@"Error %@",error.message);
 }];

Update Device Attributes

To update values of one or more device attributes. Up to seven device attributes can be updated simultaneously using this API:

#import "DeviceManagerProtocol.h"

  id deviceManager =
[[ObjectFactory sharedInstance] getDeviceManagerInstance];
[deviceManager updateDevice:DEVICE_ID duplicateAttributeValues:attributesDict success:^(CommonRetCodeResponse *response) {
          //return code = 0 indicates success
          } failure:^(SDKError *error) {
          NSLog(@"Error while updating device attributes.");
          }];

Get Time Series for an attribute

To get time series data for a time series attribute of the given device:

#import "DeviceManagerProtocol.h"

    id deviceManager =
  [[ObjectFactory sharedInstance] getDeviceManagerInstance];
[deviceManager getDeviceDecimatedTS2:DEVICE_ID propertyName:ATTRIBUTE_NAME start:TIMESTAMP end:TIMESTAMP pts:NUMBER
success:^(GetDeviceDecimatedTS2Response *response) {
    //array of  values of attribute ATTRIBUTE_NAME between start and end
} failure:^(SDKError *error) {
    NSLog(@"Error %@",error.message);
}];

Alert Management

Create Alert

To create an alert, first define the event that triggers the alert:

#import "AlertManagerProtocol.h"

AlertInfo *alertInfo = [[AlertInfo alloc]
           initWithDeviceId:DEVICE_ID
           action:AlertActionMobileNotification
           attributeName:ATTR_NAME
           operation:AlertOperationGreaterThan
           threshold:THRESHOLD
           stringThreshold:STRING_THRESHOLD
           address:ADDRESS
           msg:MESSAGE
           autoDisarm:YES
           autoDelete:NO
           autoDisable:NO
           enable:YES
           targetDeviceAttributes:nil];

And then send the alert definition to the Arrayent Cloud:

id alertManager =
  [[ObjectFactory sharedInstance] getAlertManagerInstance];

[alertManager addTrigger:alertInfo
              success:^(AddTriggerResponse *responseData) {
  NSLog(@"Alert Added Successfully.");
} failure:^(SDKError *error) {
  NSLog(@"Failed in adding alert.");
}];

Update Alert

To update definition of an alert:

#import "AlertManagerProtocol.h"

    id alertManager =
     [[ObjectFactory sharedInstance] getAlertManagerInstance];

[self updateTrigger:NEW_ALERT_WITH_OLD_ID success:^(CommonRetCodeResponse *responseData) {
    //return code = 0 indicates success
} failure:^(SDKError *error) {
    //Error
}];

Update Mobile Device Token

To update device token of an Apple phone. This device token will be used to send push notifications to device via the APNS:

#import "AlertManagerProtocol.h"

    id alertManager =
  [[ObjectFactory sharedInstance] getAlertManagerInstance];
    [alertManager updateMobile: success:^(RegisterMobileResponse *responseData) {
    //Return code = 0 indicates success
} failure:^(SDKError *error) {
    //Error
}];

Enable / Disable Single Alert

To enable or disable an alert:

#import "AlertManagerProtocol.h"

id alertManager =
    [[ObjectFactory sharedInstance] getAlertManagerInstance];

[alertManager updateTriggerStateWithId:TRIGGER_ID
              enable:YES/NO
              success:^(CommonRetCodeResponse *responseData) {
  // Trigger state updated.
} failure:^(SDKError *error) {
  // Error in updating trigger state.
}];

Enable / Disable All Alerts for All Devices

To enable or disable all alerts that have been defined for all devices owned by this user:

#import "AlertManagerProtocol.h"

id alertManager =
    [[ObjectFactory sharedInstance] getAlertManagerInstance];

[alertManager updateTriggerStateByUser:YES/NO
              success:^(CommonRetCodeResponse *responseData) {
  // Trigger state updated.
} failure:^(SDKError *error) {
  // Error in updating trigger state.
}];

Enable / Disable All Alerts for a Single Device

To enable or disable all alerts that have been defined for a single device:

#import "AlertManagerProtocol.h"

id alertManager =
    [[ObjectFactory sharedInstance] getAlertManagerInstance];

[alertManager updateTriggerStateByDevice:DEVICE_ID
              enable:YES/NO
              success:^(CommonRetCodeResponse *responseData) {
  // Trigger state updated.
} failure:^(SDKError *error) {
  // Error in updating trigger state.
}];

Delete Single Alert

To delete a single alert:

#import "AlertManagerProtocol.h"

[alertManager removeTriggerWithId:TRIGGER_ID
              success:^(CommonRetCodeResponse *responseData) {
  NSLog(@"Alert Removed Successfully");
} failure:^(SDKError *error) {
  NSLog(@"Error in removing alert");
}];

Delete All Alerts for All Devices

To delete all alerts that have been defined for all of this user’s devices:

#import "AlertManagerProtocol.h"

id alertManager =
    [[ObjectFactory sharedInstance] getAlertManagerInstance];

[alertManager removeTriggersByUser:^(CommonRetCodeResponse *responseData) {
  NSLog(@"Alerts Removed Successfully");
} failure:^(SDKError *error) {
  NSLog(@"Error in removing alerts");
}];

Delete All Alerts for a Single Device

To delete all alerts that have been defined for a single device:

#import "AlertManagerProtocol.h"

id alertManager =
    [[ObjectFactory sharedInstance] getAlertManagerInstance];

[alertManager removeTriggersByDevice:DEVICE_ID
              success:^(CommonRetCodeResponse *responseData) {
  NSLog(@"Alerts Removed Successfully");
} failure:^(SDKError *error) {
  NSLog(@"Error in removing alerts");
}];

Get alerts

To get all triggers for this user:

#import "AlertManagerProtocol.h"

    id alertManager =
        [[ObjectFactory sharedInstance] getAlertManagerInstance];
[alertManager getTriggerDetails:^(Alerts *responseData) {
      //List of all triggers for current user
 } failure:^(SDKError *error) {
      //Error
 }];

To get all triggers for a device:

   [alertManager getTriggerDetailsByDeviceId:DEVICE_ID success:^(Alerts *responseData) {
   //All triggers for this device
} failure:^(SDKError *error) {
   //Error
}];

Push Notifications

Setup

  1. Log in to https://developer.apple.com/membercenter/index.action.
  2. Go to Identifiers and select your application.
  3. Under Application Services click Edit.../../_images/push-11.png
  4. Under Production SSL Certificate click Create Certificate….../../_images/push-21.png
  5. Follow Apple’s instructions and create a certificate.../../_images/push-31.png../../_images/push-41.png../../_images/push-51.png
  6. Upload the file and download the certificate.../../_images/push-61.png
  7. Select your private key and certificate, right-click, and select Export 2 items….../../_images/push-71.png../../_images/push-81.png../../_images/push-9.png

Upload Certificate to the Arrayent Cloud

Upload your Certificates.p12 file to the Arrayent Cloud by using the “updateApplicationConfiguration” Web Service API. Refer to the Web Service API Reference Guide for more details.

Initialization

To initialize an iOS device to be able to receive push notifications, provide the mobile application name:

[APNSNotificationManager initPushWithMobileAppName:MOBILE_APPLICATION_NAME];

It is recommended to use the application bundle identifier as the mobile application name. For example:

[APNSNotificationManager initPushWithMobileAppName:[[NSBundle mainBundle] bundleIdentifier]]

Periodic Updates

Use periodic updates to call Mobile App Engine API methods on a regular interval:

TaskScheduler *taskScheduler = [[TaskScheduler alloc] init];
NSTimer *timer = [taskScheduler setTimerForAPI:GET_DEVICES
                                withParameteres:parameterArray
                                timeInterval:5.0f
                                repeats:YES
                                success:^(id responseData) {
  // API Response
} failure:^(SDKError *error) {
  // SDK Error
}];

To stop periodic updates:

[timer invalidate];

Scanning QR Codes

The Mobile App Engine contains a QR code scanner API. When an end user wants to add a device to his account, he can scan the QR code on the device. This is usually more convenient than reading a label and manually typing in a Device Code.

Setup

  1. Add ArrayentScannerView to your ViewController.
  2. Create IBOutlet in your ViewController:
    //Scanner view outlet.
    weak IBOutlet ArrayentScannerView *_qrCodeScannerView;
    //Set scannerview result block.
    [_qrCodeScannerView setResultBlock:^(NSString *result) {
     NSLog(@"Scanned Result is %@", result);
    }];
    

Ecosystem Integration

Cloud Environments

To point the engine to a different environment:

[[AppEngine sharedInstance] setEcoCloudUrl: ECO_CLOUD_URL];

ECO_CLOUD_URL must be a string like the following:

``https:://<SUBDOMAIN>.arrayent.com/ecoadaptors/``

Replace <SUBDOMAIN> with the subdomain of your cloud environment. Do not modify anything else in the URL.

Update Federated Token

The updateFederatedToken API is used to register federated token with Arrayent Ecosystem Cloud:

#import "AccountManagerProtocol.h"

id accountManager = [[ObjectFactory sharedInstance] getAccountManagerInstance];

[accountManager updateFederatedToken:token
                ecoSystemName:ecosystemName
                success:^(UpdateFederatedResponse *response) {
//API Response
} failure:^(SDKError *sdkError) {
 //SDK Error
}];