Skip to main content
Hero background

BLACKBERRY DEVELOPERS

Get Started with BlackBerry Dynamics SDK for iOS

Download, install & configure the BlackBerry Dynamics SDK for iOS.

Learn

Discover the components and benefits of the BlackBerry Dynamics Secure Mobility Platform. This resource provides information about using the BlackBerry Dynamics SDK for iOS, Android, Cordova and React Native. For more information about using the SDK for all available platforms, see the BlackBerry Dynamics SDK Documentation.

Architecture Overview

The BlackBerry Dynamics SDK provides a powerful set of tools to ISV and enterprise developers. It allows developers to focus on building commercial and business apps rather than learning how to secure, deploy, and manage those apps. The BlackBerry Dynamics Platform includes:

  • Lifecycle management

  • Security and compliance policies

  • Secure connectivity to enterprise services

  • Secure storage

  • Secure inter-app communication

  • Application configuration and application specific policies

The simplest way to understand the BlackBerry Dynamics platform is to think of it as three key components: the BlackBerry Dynamics SDK and BlackBerry servers (BlackBerry UEM) connected by BlackBerry Cloud Infrastructre (or Network Operatioons Centre). BlackBerry Dynamics provides the services and architecture to build, securely deploy, and manage apps. BlackBerry UEM includes the BlackBerry Dynamics Secure Mobility Platform and delivers the Enterprise Mobility Management (EMM) solution to securely manage devices.

With the acquisition of Good Technology by BlackBerry, BlackBerry has created a unified product with best-in-class Bring Your Own Device (BYOD), EMM, and Mobile Device Management (MDM) capabilities.

 BlackBerry Dynamics Secure Mobility Platform

The BlackBerry Dynamics (BD) platform consists of BD Runtime, the BD Network Operation Center (NOC), and BD servers.

The BD Runtime is included in every BD mobile app. The runtime has an API that gives the app access to activation, user authentication, secure storage, communication behind the firewall, and much more, all while enforcing security policies on behalf of the organization. To work with the BD Runtime, you need to download the BlackBerry Dynamics SDK for the target platform (iOS, Android, Cordova, React Native).

By including the BlackBerry Dynamics SDK in your app, you will have access to app policies, inter-app communication, secure storage, shared services, authentication delegation, single sign-on (KCD), user and app config information, and much more.

 BlackBerry UEM

BlackBerry UEM is the server component that brings everything together. It merges the best-in-class BYOD functionality of BlackBerry Dynamics with the best-in-class EMM (including MDM) solution. Administrators use UEM to manage users, groups, policies, apps, app configurations, and more.

The BlackBerry Cloud Infrastructure (or NOC) enables secure communication between your BD Runtime app and the BlackBerry Proxy. The BlackBerry Cloud also verifies the validity of user and access keys before data touches your enterprise, in addition to supporting the secure push infrastructure from server-side apps to BD Runtime apps.

UEM includes the BlackBerry Proxy servers as part of the EMM solution. They provide various services to users, devices and apps.

For app developers, you get:

  • Security and compliance policies

  • Secure connectivity to enterprise services

  • App configuration

  • App policies

  • Secure storage on-device

  • Wipe and lock functionality

  • Secure inter-app communication

  • Application lifecycle management 

BlackBerry Enterprise Mobility Server (BEMS)

The BlackBerry Dynamics platform offers enterprise mBaaS (Mobile Backend as a Service) capabilities. Many of these mBaaS services are implemented in the BlackBerry Enterprise Mobility Server (BEMS). BEMS provides programmatic connectivity through standardized APIs to enterprise systems including Microsoft SharePoint, Microsoft Teams, Microsoft Exchange, Cisco Jabber, Active Directory and more. BEMS provides APIs to invoke services such as push notifications, directory lookups, key value store, document access, IM, and presence. Developers can add these services to apps without having extensive knowledge of how to configure or connect to specific back-end systems of records.

These high quality enterprise back-end services are leveraged by BlackBerry Work, BlackBerry Connect, and other BlackBerry Secured apps. ISV and custom BlackBerry Secured apps can also make use of these services.

A Closer Look at the BlackBerry Dynamics SDKs

The BlackBerry Dynamics Platform provides a range of SDKs and plug-ins, allowing developers to work in familiar environments to build native, hybrid, and web apps. Once apps are built, developers can assume the role of an IT admin to quickly validate the management and distribution of their apps through the BlackBerry Dynamics Platform.

The BlackBerry Dynamics SDK is available natively to major platforms and development technologies including iOS and Android.

In addition, BlackBerry supports cross-platform development frameworks via dedicated BlackBerry Dynamics SDKs for Cordova and React Native.

Security Services

Security Services allow you to address security concerns about making sensitive company information available on mobile devices. You can ensure that the content that is stored on devices, exchanged with resources behind the corporate firewall, or shared between BlackBerry-secured apps is always encrypted. Since the platform uses government-grade device-independent crypto libraries, content is always encrypted. The BlackBerry Dynamics SDK includes support for the following security services:

  • Identity & Authorization APIs

  • Secure Storage APIs

  • Secure Communications APIs

  • Secure Inter-App Data Exchange APIs

Mobile Services

Mobile Services allow you to create engaging apps that will improve user productivity. You can reduce development time by using existing services -- no more building everything from scratch! And because the BlackBerry Dynamics Platform is the foundation for all services, government-grade encryption ensures end-to-end security. The BlackBerry Dynamics SDK includes support for the following mobile services:

  • Presence Service

  • Send Email Service

  • Transfer Files Service

  • Push Service

  • Directory Lookup Service

  • Docs Service

  • Launch Service

Platform Services

Platform Services make it easy to integrate apps with enterprise infrastructure (e.g., Active Directory, SharePoint, Exchange, Office 365, Lync). Focus on creating innovative apps without worrying about programming for the back-end, server maintenance, or deploying complex infrastructure. Single sign-on, horizontal scaling, HA/DR, VPN-less access to the intranet -- simply building on the current version of the BlackBerry Dynamics Platform enables it all. The BlackBerry Dynamics SDK includes support for the following mobile services:

  • Identity & Access Management

  • Single Sign-on Authentication

  • Reliable App Deployment at Scale

  • Secure Access to Corporate Data

  • App-Level Controls for IT

Install and Configure

Download, install & configure the BlackBerry Dynamics SDK for iOS Use one of the following methods to integrate the BlackBerry Dynamics SDK. It is a best practice to integrate the SDK using CocoaPods.

Software requirements

See Requirements and support for platform-specific features in the BlackBerry Dynamics SDK Development Guide.

Use CocoaPods

  1. If you don't have a Podfile refer to https://cocoapods.org/ for how to create one

  2. In your Podfile add the following reference to the BlackBerry Dynamics SDK pod:pod 'BlackBerryDynamics'

  3. To add the BlackBerry Dynamics ATSL to the target app for UI tests, in your Podfile add the following pod:pod 'BlackBerryDynamicsAutomatedTestSupportLibrary'
    For more information, see Add automated testing to your BlackBerry Dynamics iOS app.

  4. If default. xcconfig is used by your application, add the following to the end of your Podfile:
    post_install do |installer|
        # Append configuration from default.xcconfig to configuration generated by Cocoapods
        if Dir.glob("**/default.xcconfig").first()
            system("find Pods -name 'Pods-*.xcconfig' -exec sh -c 'cat 'find . -name default.xcconfig' »> $1' -- (} \ \;")
        end
    end

  5. Install the pods, then open your workspace file to see the project in Xcode:$ pod install 

Use CocoaPods

  1. If you don't have a Podfile refer to https://cocoapods.org/ for how to create one

  2. In your Podfile add the following reference to the BlackBerry Dynamics SDK pod:pod 'BlackBerryDynamics'

  3. To add the BlackBerry Dynamics ATSL to the target app for UI tests, in your Podfile add the following pod:pod 'BlackBerryDynamicsAutomatedTestSupportLibrary'
    For more information, see Add automated testing to your BlackBerry Dynamics iOS app.

  4. If default. xcconfig is used by your application, add the following to the end of your Podfile:
    post_install do |installer|
        # Append configuration from default.xcconfig to configuration generated by Cocoapods
        if Dir.glob("**/default.xcconfig").first()
            system("find Pods -name 'Pods-*.xcconfig' -exec sh -c 'cat 'find . -name default.xcconfig' »> $1' -- (} \ \;")
        end
    end

  5. Install the pods, then open your workspace file to see the project in Xcode:$ pod install 

Use the files available in the SDK package

  1. Extract the contents of the BlackBerry_Dynamics_SDK_for_iOS_<version>_dylib.tar.gz file into a directory.

  2. From the directory Frameworks in the extracted SDK package copy all the framework files into your desired directory.

  3. Import the frameworks into the project by dragging them from the directory

  4. In the Frameworks, Libraries and Embedded Content list of the project target:

    • Add BlackBerryDynamics.xcframework, BlackBerryCerticom.xcframework, BlackBerryCerticomSBGSE.xcframework; if needed add the BlackBerryDynamicsAutomatedTestSupportLibrary.xcframework

    • Set all of the above frameworks to Embed and Sign so that Xcode will change the project file by adding the frameworks to the Embed Frameworks step in the Build Phases and will configure the Runpath Search Paths accordingly.

Develop

Develop a BlackBerry Secured App for iOS

New App

The easiest way to get started with the BlackBerry Dynamics SDK for iOS is to use the BlackBerry Dynamics sample apps that are available in the SDK package.

Perform the following steps to use the apps:

  1. Run pod install to install the project dependencies including BlackBerry Dynamics

  2. Launch Xcode and open the project.

  3. Edit the Bundle ID to your own.

  4. Edit the URL identifier and URL Schemes in the Info.plist.

  5. Edit the GD Application ID to your own in the Info.plist.
    Note:  The general form is com.yourcompany.application_name (lowercase only, no spaces, and must not begin with com.good or com.blackberry). The same id can be used for multiple apps on different platforms, such as iOS and Android, so it is a best practice to avoid platform-specific information (example: com.yourcompany.ios.application).

  6. Build, deploy, and run the app.

Existing App

Add and configure the BlackBerry Dynamics SDK

In order to add the BlackBerry Dynamics SDK into an existing project, perform the actions described in the section "Install & Configure".

Once the BlackBerry Dynamics SDK has been added to the project, perform the steps below to configure it.

  1. Set the BlackBerry Dynamics Application ID and BlackBerry Dynamics Version in the app's Info.plist.

    GDApplicationID
    The general form is com.yourcompany.application_name (only lower case, no spaces, and must not begin with com.good or com.blackberry).
    The same id can be used for multiple apps on different platforms such as iOS and Android. It’s recommended to avoid including the platform-specific information (example: com.yourcompany.ios.application).

    GDApplicationVersion
    A version number is four parts. Use 1.0.0.0 for the first version of the app with BlackBerry Dynamics SDK
    It is not recommended to change the version often unless it’s required to provide different access to specific users or to differentiate a new app from existing versions of the app due to newly added services.

  2. Add a variable reference in the URL scheme and URL identifier specifiers. Add the following code into the info.plist.
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLName</key>
            <string>Bundle_Identifier_of_your_app</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>Bundle_Identifier_of_your_app.sc2</string>
                <string>Bundle_Identifier_of_your_app.sc2.1.0.0.0</string>
                <string>Bundle_Identifier_of_your_app.sc3</string>
                <string>com.good.gd.discovery</string>
            </array>
        </dict>
    </array>

  3. The BlackBerry Dynamics SDK needs to use the device camera and might be configured to use FaceID authentication, therefore the keys NSFaceIDUsageDescription and NSCameraUsageDescription need to be added to the InfoPlist.strings file if the existing app doesn't do it already.
    "NSFaceIDUsageDescription" = "Enables authentication without a password.";
    "NSCameraUsageDescription" = "Allow camera usage to scan a QR code";

Integrate the BlackBerry Dynamics SDK

To work as a BlackBerry Dynamics app, the app must use the GDiOSDelegate protocol and the launch code execution must be delayed until the end user has been authorized.

Below are the main steps needed:

  1. Implement the GDiOSDelegate protocol to receive GDAppEvent objects from the BlackBerry Dynamics SDK

  2. Use GDAppEvent provided in the handler method of the GDiOSDelegate to process authorization events.

  3. Switch off the automatic loading of the main storyboard. Instead, load the main storyboard programmatically when the end user has been authorized.

  4. Kick off the authorization process handled by the BlackBerry Dynamics SDK in the app's didFinishLaunchingWithOptions, invoking the method GDiOS.sharedInstance().authorize()

Modify the UIApplicationDelegate to defer the loading of the main UI until the end user is authorized by the BlackBerry Dynamics SDK.

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
        [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        // Set the AppDelegate in the GDiOSDelegate
        AppGDiOSDelegate.sharedInstance.appDelegate = self

        // Trigger end-user authorization process with BlackBerry Dynamics SDK
        GDiOS.sharedInstance().authorize(AppGDiOSDelegate.sharedInstance)

        return true
    }
}

Implement the GDiOSDelegate to handle events from the BlackBerry Dynamics SDK and load the main UI when the authorized event is received.

import BlackBerryDynamics.Runtime

class AppGDiOSDelegate : NSObject, GDiOSDelegate {

    static let sharedInstance = AppGDiOSDelegate()

    var hasAuthorized = false
    weak var appDelegate: AppDelegate?

    func handle(_ anEvent:GDAppEvent) {
        switch anEvent.type {
        case .authorized:
            self.onAuthorized(anEvent);
            break
        case .notAuthorized:
            self.onNotAuthorized(anEvent);
            break
        case .remoteSettingsUpdate:
            //A change to application-related configuration or policy settings.
            break
        case .servicesUpdate:
            //A change to services-related configuration.
            break
        case .policyUpdate:
            //A change to one or more application-specific policy settings has been received.
            break
        default:
            print("Event not handled: '\(anEvent.message)'")
            break
        }
    }

    func onAuthorized(_ anEvent: GDAppEvent) {
        // Handle the BlackBerry Dynamics SDK authorized event
        switch anEvent.code {
        case .errorNone :
            if (!hasAuthorized) {
                // Prepare main storyboard and root view controller
                let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
                let rootViewController = mainStoryboard.instantiateInitialViewController()

                self.appDelegate!.window?.rootViewController = rootViewController
                hasAuthorized = true
            }
        default:
            assert(false, "Authorized startup with an error")
            break
        }
    }
}

Deploy and Test

Deploy your BlackBerry Dynamics app to a smartphone, tablet, or emulator for testing purposes. You require: An Internet connection A smartphone, tablet, or emulator supported by BlackBerry Dynamics A BlackBerry UEM server or use the Enterprise Simulation Mode Note: It is possible to perform automated testing of the BlackBerry Dynamics SDK utilising the APIs provided in the optional library BlackBerry Dynamics Automated Test Support Library (ATSL), see below for more details on how to integrate and use it.

Enterprise Simulation Mode

To run and test any BlackBerry Dynamics app, a BlackBerry UEM server is needed but, with considerable limitations, Enterprise Simulation Mode can be used to test an app without a connection to a BlackBerry UEM server

In Enterprise Simulation Mode, there is no user authentication at the enterprise level, so there will be no communication through the enterprise firewall. If the app requires a connection behind the firewall then a BlackBerry UEM server is needed.

Important: the Enterprise Simulation Mode is not intended for a production environment and it is limited to run on an iOS simulator only.

 

Although Enterprise Simulation Mode is not suitable for the production deployment of an app, it is useful during development, and for verifying proper execution and behavior when migrating existing apps to BlackBerry Dynamics.

In simulation mode, a valid activation key is not required to open the app because there is no direct communication with BlackBerry Dynamics servers. Communication with the BlackBerry Dynamics NOC, however, continues to take place.

 

To enable Enterprise Simulation Mode for a BlackBerry Dynamics app, add the following to the Info.plist file:

<key>GDLibraryMode</key>
<string>GDEnterpriseSimulation</string>

To disable it, change the value to GDEnterprise or remove the key altogether.

 

When a BlackBerry Dynamics app is running for the first time on a target, it needs to be activated with the BlackBerry Dynamics server. In Enterprise Simulation Mode, any email address and any 15-character access key are valid to complete the activation process. After the app is activated, the app will prompt the user to create a password.

The Password Requirements link at the bottom of the screen provides guidance on the required password complexity. When not running in Enterprise Simulation Mode the password complexity is controlled via policies managed by your IT admin through the UEM management console.

 

Enterprise Simulation Mode presents the following differences from standard enterprise execution:

  • [Simulated] will appear in the BlackBerry Dynamics Runtime user interface

  • Any email address and activation key will be accepted for enterprise activation

  • No information is actually sent to enterprise servers, including the email address and activation key

  • The provisioning and policy setup flow is simulated in the UI

  • A hard-coded set of security and compliance policies are in effect; authentication is not delegated

  • When run on a real device, not an emulator, the app will be wiped

  • Attempts to change the mode from GDEnterprise to GDEnterpriseSimulation for an app that is already installed on a device will result in the app being wiped

  • No lost-password recovery is available

  • Inter-container Communication (ICC) cannot be used, which means that the BlackBerry Dynamics Services API cannot be used

Otherwise, the secure storage, secure communication, and push channel APIs are all available in Enterprise Simulation Mode.

The communication APIs will not be able to connect to any enterprise app servers through the UEM server, although direct connections to enterprise app servers can still be made, if, for example, the iOS Simulator is running on a machine that is on the enterprise network or VPN.

Using BlackBerry UEM server

BlackBerry UEM or BlackBerry UEM Cloud instance is required to perform testing on an actual smartphone or tablet.

Follow the required steps to configure a BlackBerry Secured app for testing in UEM. If you do not yet have a UEM instance in place, you can configure one with a free developer trial license. Click here to generate a trial license and start configuring your server.

Once the servers are in place, continue with the following steps.

1) Configure the app on BlackBerry UEM or BlackBerry UEM Cloud

The first thing to do is to define the app in the BlackBerry UEM 

  1. Log in to the BlackBerry UEM management console.

  2. Click Apps > New App > Internal BlackBerry Dynamics app entitlements > Next.

  3. Specify the BlackBerry Dynamics Entitlement ID and BlackBerry Dynamics Entitlement Version that was set in the Info.plist file. For example, com.mycompany.testApp and 1.0.0.0.

  4. Click Add.

Your application will be included in the list of available apps. If you need to provide additional configuration parameters for your app, such as whitelisting servers or configuring an app policy, select your app from the list and configure it as necessary.

Recommendation: Add the Bundle ID to the app’s configuration. This allows the use of Easy Activation, which avoids the requirement of entering an access key when first starting the app. This is also required if your app uses any BlackBerry AppKinetics services.

To add these values:

  1. Click the app.

  2. On the iOS tab, enter the appropriate value

  3. Click Save.

2) Disable Anti-Debug detection

BlackBerry UEM has the capability to prevent debug versions of BlackBerry Dynamics apps from being run. To allow for app development, this must be disabled in the Compliance profile assigned to the user used for testing.

To disable the policy, follow the steps below:

  1. Log in to the UEM management console.

  2. On the left menu, click Policies and profiles > Compliance.

  3. Open the compliance profile assigned to the test user.

  4. On the iOS tab, if Jailbroken OS is checked, ensure that Enable anti-debugging for BlackBerry Dynamics apps is not selected.

3) Entitle app users

After an app is registered in a BlackBerry UEM server, users must be entitled to install and use the app. Individual users or user groups can be entitled to an app. For production deployment, it’s recommended to use user groups. When developing or testing, individual users can be used.

To entitle an app to an individual user, follow the steps below:

  1. Log in to the UEM management console.

  2. Search for and select a user account.

  3. In the Apps section in the user profile, click +.

  4. Search for and select your app.

  5. Click Next.

  6. Leave the Disposition as optional (installation will not be forced) and click Assign.

  7. Depending on your authentication delegate configuration, you may need to generate an Activation Password that will be used when the app is run for the first time after installation.

To generate a new Activation Password:

  1. In the user's profile, under the Summary tab, click Set activation password.

  2. In the Activation option drop-down list, click Default device activation.

  3. In the Activation password drop-down list, click Set device activation password.

  4. In the Device activation password text field enter the password to be used when the app is run for the first time after installation.

  5. For development purposes, it can be useful to extend the Activation period expiration to the maximum allowed (30 days)

  6. Click Submit.

  7. The user receives an email with the credentials and a QR code that can be used to activate the app when it's first run after installation.
    The email sent to the user can be seen also from the UEM console by clicking on the link "View activation email"

  8. Install the app to the intended target using the preferred deployment method (including via Xcode).

  9. When prompted select an activation type between the ones available 

    • Use "enter credentials" to use email and activation password directly.

    • Use "Scan QR code" if the app is running on a device with a camera and the QR code from the activation email is available to scan even from a screen.

Automated testing of BlackBerry Dynamics SDK

The BlackBerry Dynamics SDK includes the BlackBerry Dynamics Automated Test Support Library (ATSL) to support automated testing for your BlackBerry Dynamics apps.

The library includes helper functions for testing common user interactions in BlackBerry Dynamics apps, such as activation and authorization. The configuration and structure of the library are compatible with the tools offered by Apple for user interface testing.

It makes use of the following components:

  • XCTest framework

  • Accessibility identifiers

For more information about these components and iOS user interface testing, see Apple Documentation Archive: User Interface Testing.

You can use the BlackBerry Dynamics library and the native library components mentioned above to automate the building, execution, and reporting of your application tests.

Since the BlackBerry Dynamics ATSL is delivered as a framework, you cannot make your own changes to it.

Integrate the BlackBerryDynamicsAutomatedTestSupportLibrary framework

The BlackBerryDynamicsAutomatedTestSupportLibrary framework can be integrated into the test target of a project as any other framework in the BlackBerry Dynamics SDK.

Refer to the instructions in the section "Install & Configure" for detailed steps.

Using the BlackBerryDynamicsAutomatedTestSupportLibrary framework

In the same directory as the test code, create a file credentials.json with content similar to below:

{
    "GD_TEST_PROVISION_EMAIL":"testUser@mydomain.com",
    "GD_TEST_PROVISION_ACCESS_KEY":"activationPassword",
    "GD_TEST_PROVISION_PASSWORD":"passwordForApplication"
}

Note: The fields GD_TEST_PROVISION_EMAIL and GD_TEST_PROVISION_PASSWORD could be hard-coded but if the test operates on a non-activated app then the GD_TEST_PROVISION_ACCESS_KEY must be regenerated before the tests start via the BlackBerry UEM REST APIs or it has to be set manually in the BlackBerry UEM server with an extended validity (set the Activation period expiration to 30 days for example).

If the test doesn't reinstall the app and the app is provisioned, the value of GD_TEST_PROVISION_ACCESS_KEY won't be used as the BlackBerry Dynamics SDK can be authorized simply using the password set during the initial provisioning of the app, taken from the field GD_TEST_PROVISION_PASSWORD.

 

To use BBDAutomatedTestSupport class in any test, follow these steps:

  1. Instantiate the main class BBDAutomatedTestSupport
    let ats = BBDAutomatedTestSupport.sharedInstance()

  2. Load the credentials with
    ats.fetchCredentials()

  3. Define the XCUIApplication object to use and set up the BBDAutomatedTestSupport to use it.
    let application = XCUIApplication()
    ats.setupBBDAutomatedTestSupport(with: application, for: self)

  4. Launch the authorization flow with
    XCTAssertTrue(ats.loginOrProvisionBBDApp(), "Could not authorize the app")

  5. Verify that the authorization process was successful and the app main UI is shown with something like
    XCTAssertTrue(ats.isScreenShown("AppRootControllerIdentifier", timeout: 120), "BlackBerry Dynamics SDK authorization was successful but the main app UI was not shown")

Notes:

  • The json file with credentials can have a different name and/or path, it can be loaded using variants of fetchCredentials() function.

  • Biometric authentication is only partially supported by the BlackBerryDynamicsAutomatedTestSupportLibrary because, by its own nature, it's limited to being tested automatically only on a simulator.

Success! Continue

Congratulations on developing your first BlackBerry Dynamics secured app! You can continue to explore the available APIs and developer resources. Learn about some of the common APIs below.

The code snippets referenced in this section are available in the iOS sample apps from the BlackBerry GitHub site. Download the BlackBerry Dynamics iOS Samples repository and see these projects:

  • Basic-iOS-Objective-C

  • Basic-iOS-Swift

  • Dynamics-iOS-Objective-C

  • Dynamics-iOS–Swift

  • Dynamics-SwiftUI-Sample

Use the BlackBerry Dynamics File System

The secure file system is part of the BlackBerry Dynamics Secure Storage feature. For apps, the BlackBerry Dynamics secure file system behaves like the default file manager system, with the following differences:

  • All data within the secure file system is stored on the device in an encrypted form.

  • Directory and file names are also encrypted.

  • There is no current working directory in the secure file system. Paths should always be specified as absolute paths, beginning with a / character.

  • The secure file system cannot be accessed until BlackBerry Dynamics authorization processing is complete. For more information, see authorize in the GDiOS class reference.

Encryption and decryption are transparent to the app code:

  • File-writing interfaces accept plain data. The BlackBerry Dynamics Runtime encrypts the data and stores it on the device.

  • When a file-reading interface is utilized, the BlackBerry Dynamics Runtime decrypts what was stored and returns plain data.

  • Path access interfaces accept plain parameters for directory and file names. The BlackBerry Dynamics Runtime encrypts the parameter values to create paths in the secure store.

  • The directory and file names provided as return values are plain. The BlackBerry Dynamics Runtime decrypts paths in the secure store to generate the return values.

The encryption method used by the BlackBerry Dynamics Runtime generally requires that the user has entered a security password from which an encryption key is derived.

Since the GDFileManager class is a subclass of the native NSFileManager class, minimal changes are required. Simply replace references to NSFileManager with references to GDFileManager.

Comparing before and after code snippets from the two sample apps, you’ll observe the following changes:

Native

import Foundation
...

func writeToNativeFile() -> Bool {
    let text = "Text not protected."
    let fileData = text?.data(using: .utf8)
    let filePath = documentsFolderPathForNamed(name: "NativeFileTest.txt")

    //Create a plain file using FileManager
    let fileCreated = FileManager.default()
        .createFile(atPath: filePath,
            contents: fileData,
            attributes: nil)
    return fileCreated
}

Dynamics

import BlackBerryDynamics.SecureStore.File

...

func writeToGDFile() -> Bool {
    let text = "Text to be protected by BlackBerry Dynamics."
    let fileData = text?.data(using: .utf8)
    let filePath = documentsFolderPathForNamed(name: "EncryptedFileTest.txt")

    //Create an encrypted file using GDFileManager
    let fileCreated = GDFileManager.default()
        .createFile(atPath: filePath,
                contents: fileData,
                attributes: nil)
    return fileCreated
}

 

Use the BlackBerry Dynamics SQLite Database

The secure SQL database is part of the BlackBerry Dynamics Secure Storage feature. Data stored in the secure SQL database is encrypted on the device by the BlackBerry Dynamics Runtime. The BlackBerry Dynamics secure SQL database is based on the SQLite library. Encryption is added by BlackBerry Dynamics transparently to the app. A secure SQL database cannot be accessed until BlackBerry Dynamics authorization processing is complete.

BlackBerry Dynamics apps access the secure database using replacements for the native SQLite. To access the replacement classes instead of the native classes, change the import statement sqlite3.h to GD_C.SecureStore.SQLite (for Swift sources) or BlackBerryDynamics/GD_C/sqlite3enc.h (for Objective-C sources)

For more information about using SQLite databases, refer to the Secure SQL Database API.

If you compare the modifications required for SQLite between the native samples and the BlackBerry Dynamics sample, you’ll notice that the changes are minimal. Updates are required to the import statements and opening and importing of an encrypted database. The rest of the SQLite in the app can remain as is. Here are the changes that were made:

Native

import SQLite

...

func openDatabase() -> Bool {
    let fileUrl = try! FileManager.default
            .url(for: .documentDirectory,
                in: .userDomainMask,
                appropriateFor:nil,
                create: false)
        .appendingPathComponent("plain_database.db")
    var db:OpaquePointer? = nil
    let result = sqlite3_open(fileUrl.path, &db)

    return result == SQLITE_OK
}

Dynamics

import GD_C.SecureStore.SQLite

...

func openDatabase() -> Bool {
    let fileUrl = try! FileManager.default
                .url(for: .documentDirectory,
                    in: .userDomainMask,
                    appropriateFor:nil,
                    create: false)
                .appendingPathComponent("encrypted_database.db")
    var db:OpaquePointer? = nil
    let result = sqlite3enc_open(fileUrl.path, &db)

    return result == SQLITE_OK
}

Use the BlackBerry Dynamics HTTP/HTTPS Connections

GDURLLoadingSystem

BlackBerry Dynamics applications can use the native URL Loading System. The native URL Loading System classes can be used to communicate with app servers that are residing behind an enterprise firewall or on the Internet. Once a connectivity profile is configured in BlackBerry UEM for secure communication, the native class NSURLSession or NSURLConnection should work as is.

See the BlackBerry Dynamics SDK API Reference and review the GDURLLoadingSystem class and NSURLSession support.

GDHttpRequest API as an alternative approach

In addition to the GDURLLoadingSystem, you can use the GD HTTP Request API to send HTTP requests, such as GET and POST, from the device to an app server. The app server can be on the Internet or behind the enterprise firewall as well. The GD HTTP Request API is based on the XML Http Request (XHR) standard.

BlackBerry Dynamics secure communications support HTTPS, using a Secure Socket Layer connection or SSL/TLS to send the HTTP request and receive the response. HTTP and HTTPS requests can be relayed by an HTTP or HTTPS proxy that resides on the Internet or behind the enterprise firewall. Authentication with the proxy is supported.

When making HTTPS requests through an HTTP proxy, SSL/TLS certificate verification must be disabled. Certificate verification while using an HTTP proxy is not supported. BlackBerry Dynamics HTTP data communication does not go via the proxy specified in the device's native settings, if any.

The BlackBerry Dynamics Runtime supports Basic Access, Digest Access, NTLM, and Kerberos for authentication with HTTP servers. Except for Kerberos, all of these mechanisms are also supported for authentication with HTTP proxies. The BlackBerry Dynamics Runtime supports Kerberos version 5 authentication.

By default, HTTP cookies received through BlackBerry Dynamics secure communication are handled automatically.

For more information, see the GDHTTPRequest class reference. The changes required for the GD HttpRequest class are listed below:

// Open a requested URL using URLSession
func requestData(url : String) {
    let nsUrl = URL(string: url)
    let urlRequest = URLRequest(url: nsUrl!)
    let session = URLSession.init(configuration: URLSessionConfiguration.default, delegate: self,
                delegateQueue: OperationQueue.init())


    let task = session.dataTask(with: urlRequest,
                completionHandler: { (data, response, error) in
                    DispatchQueue.main.async {
                        print(response ?? "res")
                    }
                })
    task.resume()
}

Make BlackBerry Dynamics Socket Connections

The GDSocket API is asynchronous and state-based. The app attaches its own event-handler callbacks to the GD Socket object. The callback functions are invoked when socket events occur, or when the socket changes state. The API functions that can be called by the app depend on the socket's state.

Sending data through a GDSocket is a two-stage operation. The first stage is to add the data to the socket's outbound buffer. The socket's outbound buffer is represented by the writeStream property and is accessed using the GDDirectByteBuffer API. The second stage is to send the contents of the buffer through the socket connection. To send the buffer, call the write function.

Reading data from a GDSocket is asynchronous. When data is received at the device, the data is stored in the socket's inbound buffer. The app is then notified that data is available to read, by invocation of the delegate onRead callback. In the callback, the app consumes the received data from the inbound buffer. The inbound buffer is represented by the readStream property and is accessed using the GDDirectByteBuffer API.

The GDSocket API supports the use of SSL/TLS to send and receive data. By default, the BlackBerry Dynamics runtime does not offer the TLSv1.1 or TLSv1.2 protocols for SSL/TLS connections with an app server.

These protocols can be enabled, as follows:

  1. Add a new row to the application's Info.plist file:

    • Key:  GDControlTLSVersions

    • Type:  String  (the default)

  2. Set the value to:

    • GDEnableTLS1.1  to enable the TLSv1.1 protocol.

    • GDEnableTLS1.2  to enable both TLSv1.1 and TLSv1.2 protocols.

    As an alternative, the value can instead be an array containing one or both of the above strings as separate items.

The GDSocket connections and HTTP requests can be used to connect to servers that are behind the enterprise firewall. The address of the destination app server must be registered in the BlackBerry UEM management console.

  • The address could be registered as the app's server or as an additional server.

  • The app server configuration in the UEM server can be obtained in the app code by using the getApplicationConfig(GDiOS) function.

The connection to the app server will be made through the BlackBerry Dynamics proxy infrastructure. Verify the status of the mobile app's connection to the proxy infrastructure before attempting to open the socket or sending the HTTP request.

The changes required for the GDSocket class are listed below:

Native

import CoreFoundation


...


class SocketHelper: StreamDelegate {

    func connectToServer() {
        var readStream: Unmanaged<CFReadStream>?
        var writeStream: Unmanaged<CFWriteStream>?

        var inputStream: InputStream
        var outputStream: OutputStream

        let port = UInt32(80)
        let host = "developer.blackberry.com" as CFString
                    CFStreamCreatePairWithSocketToHost(nil, host, port, &readStream, &writeStream)

        inputStream = readStream!.takeRetainedValue()
        outputStream = writeStream!.takeRetainedValue()

        inputStream.delegate = self
        outputStream.delegate = self

        inputStream.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default)
        outputStream.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default)

        inputStream.open()
        outputStream.open()

    }

    func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
        ....
    }

}

Dynamics

import BlackBerryDynamics.SecureCommunication

...

class GDSocketHelper: GDSocketDelegate {

    func connectToServer() {
        let port = Int32(80)
        let host = NSString(string: "developer.blackberry.com")
        let gdSocket = GDSocket(host.utf8String!, onPort: port, andUseSSL: false)

        gdSocket.delegate = self
        gdSocket.connect()
    }

    func onOpen(_ socket: Any) {
        let gdSocket = socket as! GDSocket;
        let httpString = NSString(string:
                "GET http://developer.blackberry.com/ HTTP/1.1\r\n" +
                "Host:developer.blackberry.com:80\r\n" +
                "Connection:close\r\n" +
                "\r\n")

        gdSocket.writeStream?.write(httpString.utf8String!)
        gdSocket.write()
    }

    func onRead(_ socket: Any) {
        let gdSocket = socket as! GDSocket;
        let str = gdSocket.readStream?.unreadDataAsString()
        DispatchQueue.main.async {
            print(String(describing: str))
        }
        gdSocket.disconnect()
    }

    func onClose(_ socket: Any) {
        let gdSocket = socket as! GDSocket;
            // do something if necessary
    }
}

Secure Copy, Paste and AutoFill Operations

Copy and Paste

The BlackBerry Dynamics runtime may secure or block text in transit to or from the clipboard, depending on the policies for data leakage prevention (DLP) policy configured in BlackBerry UEM. The runtime secures text by encrypting it when it is cut or copied to the device clipboard, and then decrypting it when it is pasted from the clipboard. On iOS, these operations are handled automatically by the BlackBerry Dynamics Runtime.  No coding changes are required to support this on iOS.

Disable AutoFill

To block password AutoFill, make the TextField an implementation of BBDAutoFillBlockerField. The BBDAutoFillBlockerField class is open source and demonstrated in the AutoFillBlockingSample.