Skip to content

Breinify/brein-api-library-ios

Repository files navigation

#BreinifyApi

Breinify API iOS Library

Breinify's DigitalDNA API puts dynamic behavior-based, people-driven data right at your fingertips.

Version Carthage compatible License Platform

Step By Step Introduction

What is Breinify's DigitialDNA

Breinify's DigitalDNA API puts dynamic behavior-based, people-driven data right at your fingertips. We believe that in many situations, a critical component of a great user experience is personalization. With all the data available on the web it should be easy to provide a unique experience to every visitor, and yet, sometimes you may find yourself wondering why it is so difficult.

Thanks to Breinify's DigitalDNA you are now able to adapt your online presence to your visitors needs and provide a unique experience. Let's walk step-by-step through a simple example.

Requirements

  • iOS 9.3+
  • Xcode 8.0+
  • AppCode 2016.2
  • Swift 2.3

Installation

CocoaPods

Step 1 - Install CocoaPods

Installing the BreinifyApi via the iOS CocoaPods automates the majority of the installation process. Before beginning this process please ensure that you are using Ruby version 2.0.0 or greater. Don’t worry, knowledge of Ruby syntax isn’t necessary to install the Library.

Simply run the following command to get started:

$ sudo gem install cocoapods

#####Note: If you are new to Cocopods further details can be found here

Step 2 - Create Podfile

To integrate BreinifyApi into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.3'
use_frameworks!

target '<Your Target Name>' do
    pod 'BreinifyApi'
end

If you are running Swift 2.3 we recommend to add the following lines to your Podfile as well:

 post_install do |installer|
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings['SWIFT_VERSION'] = '2.3'  ## or '3.0'
      end
    end
  end

Step 3 - Install the BreinifyApi

To install the BreinifyApi, navigate to the directory where your Podfileresides within your terminal and run the following command:

$ pod install

The BreinifyApi Dependency will be added and a XCode workspace will be generated. This workspace file bundles your original Xcode project, the BreinifyApi library, and its dependencies.

At this point you should be able to open the new Xcode project workspace created by CocoaPods. From now on, you have to use .xcworkspace instead of .xcodeproj.

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. You can install Carthage with Homebrew using the following command:

Step 1 - Intall Carthage

You can install Carthage with homebrew.

$ brew install carthage

Make sure you are running the latest version of Carthage.

$ brew upgrade carthage

Step 2 - Create Cartfile

To integrate BreinifyApi into your Xcdoe project using Carthage, specify in your Cartfile:

github "Breinify/brein-api-library-ios"

Step 3 - Install the BreinifyApi

To install the BreinifyApi, navigate to the directory where your Cartfileresides within your terminal and run the following command:

$ carthage update

This will fetch dependencies into a Carthage/Checkouts folder. Drag BreinifyApi.framework into your Xcode project.

Dependencies

BreinifyApi includes the following two libraries:

  • Alamofire
  • IDZSwiftCommonCrypto

License

BreinifyApi is available under the MIT license. This applies also for Alamofire and IDZSwiftCommonCrypto. See the LICENSE file for more info.

BreinifyApi Integration

Step 1: Request API-key

In order to use the library you need a valid API-key, which you can get for free at https://www.breinify.com. In this example, we assume you have the following api-key:

772A-47D7-93A3-4EA9-9D73-85B9-479B-16C6

Step 2: Include the BreinifyApi module

Add the following line to your swift file (e.g. ViewController.swift)

import BreinifyApi

Step 3: Configure the Library

The BreinifyApi needs to be configured with an instance of BreinConfig containing a valid API-key and a secret (optional).

This would look like this:

// this has to be a valid api key and secret
let validApiKey = "772A-47D7-93A3-4EA9-9D73-85B9-479B-16C6"
let validSecret = "iTttt=0=w2244="

// create the configuration object
let breinConfig = BreinConfig(apiKey: validApiSecret, secret: validSecret)
    
// set configuration
Breinify.setConfig(breinConfig)

Step 3: Start using the library

Placing activity triggers

The engine powering the DigitalDNA API provides two endpoints. The first endpoint is used to inform the engine about the activities performed by visitors of your site. The activities are used to understand the user's current interest and infer the intent. It becomes more and more accurate across different users and verticals as more activities are collected. It should be noted, that any personal information is not stored within the engine, thus each individual's privacy is well protected. The engine understands several different activities performed by a user, e.g., landing, login, search, item selection, or logout.

The engine is informed of an activity by executing Breinify.activity(...).

// create a user you are interested in with his email
let breinUser = BreinUser()

typealias apiSuccess = (result:BreinResult?) -> Void
typealias apiFailure = (error:NSDictionary?) -> Void

// callback in case of success
let successBlock: apiSuccess = {
     (result: BreinResult?) -> Void in
     print("Api Success : result is:\n \(result!)")
}

// callback in case of a failure
let failureBlock: apiFailure = {
     (error: NSDictionary?) -> Void in
     print("Api Failure: error is:\n \(error)")
}

// set additional user information (optional)
breinUser.setFirstName("Fred")
         .setLastName("Firestone")

// invoke activity call
do {
    try Breinify.activity(breinUser,
         activityType: "login",
             category: "home",
          description: "Login-Description",
              success: successBlock,
              failure: failureBlock)
  } catch {
    print("Error is: \(error)")
} 

That's it! The call will be run asynchronously in the background and depending of the result the successBlock or failureBlock callback will be invoked.

Placing temporalData triggers

Temporal Intelligence API provides temporal triggers and visualizes patterns enabling you to predict a visitor’s dynamic activities. Currently this will cover:

  • Current Weather
  • Upcoming Holidays
  • Time Zone
  • Regional Events

They can be requested like this:

let failureBlock: apiFailure = {
     (error: NSDictionary?) -> Void in
     print("Api Failure : error is:\n \(error)")
}
     
let successBlock: apiSuccess = {
    (result: BreinResult?) -> Void in
    print("Api Success : result is:\n \(result!)")

    if let holiday = result!.get("holidays") {
        print("Holiday is: \(holiday)")
    }
    if let weather = result!.get("weather") {
        print("Weather is: \(weather)")
    }
    if let location = result!.get("location") {
        print("Location is: \(location)")
    }
    if let time = result!.get("time") {
        print("Time is: \(time)")
    }
}

do {
    let user = BreinUser(email: "fred.firestone@email.com")
          .setFirstName("Fred")
          .setTimezone("America/Los_Angeles")
          .setLocalDateTime("Sun Dec 25 2016 18:15:48 GMT-0800 (PST)")

    try Breinify.temporalData(user,
              success: successBlock,
              failure: failureBlock)
     } catch {
         print("Error")
     }
 }
Placing look-up triggers

Look-ups are used to retrieve dedicated information for a given user. This code snippet assumes that the typealias and further objects from above are in the same scope.

typealias apiSuccess = (result:BreinResult?) -> Void
typealias apiFailure = (error:NSDictionary?) -> Void

// create a user you are interested in with his email (mandatory field)
let breinUser = BreinUser(email: "fred.firestone@email.com")

// define an array of subjects of interest
let dimensions: [String] = ["firstname", "gender",
                                "age", "agegroup", 
                                "digitalfootprint", "images"]

// wrap this array into BreinDimension object
let breinDimension = BreinDimension(dimensionFields: dimensions)

// invoke the lookup
let successBlock: apiSuccess = {(result: BreinResult?) -> Void in
     print ("Api Success!")

     if let dataFirstname = result!.get("firstname") {
         print ("Firstname is: \(dataFirstname)")
     }

     if let dataGender = result!.get("gender") {
         print ("Gender is: \(dataGender)")
     }

     if let dataAge = result!.get("age") {
         print ("Age is: \(dataAge)")
     }

     if let dataAgeGroup = result!.get("agegroup") {
         print ("AgeGroup is: \(dataAgeGroup)")
     }

     if let dataDigitalFootprinting = result!.get("digitalfootprinting") {
            print ("DigitalFootprinting is: \(dataDigitalFootprinting)")
     }

     if let dataImages = result!.get("images") {
         print ("DataImages is: \(dataImages)")
     }
 }

let failureBlock: apiFailure = {(error: NSDictionary?) -> Void in
     print ("Api Failure : error is:\n \(error)")
}

do {
   try Breinify.lookup(breinUser,
        dimension: breinDimension,
          success: successBlock,
          failure: failureBlock)
} catch {
    print("Error is: \(error)")
}

Full working sample

Let’s navigate back to Xcode and inside the IDE, go to ViewController.swift. The code should look like this:

import UIKit
import BreinifyApi

class ViewController: UIViewController {

    typealias apiSuccess = (result: BreinResult?) -> Void
    typealias apiFailure = (error: NSDictionary?) -> Void

    // create Brein user
    let breinUser = BreinUser()         

    // invoked when activityButton has been pressed
    @IBAction func actionButtonPressed(sender: AnyObject) {

        let successBlock: apiSuccess = {
            (result: BreinResult?) -> Void in
            print("Api Success : result is:\n \(result)")
        }

        let failureBlock: apiFailure = {
            (error: NSDictionary?) -> Void in
            print("Api Failure : error is:\n \(error)")
        }

        // set additional user information
        breinUser.setFirstName("Fred")
                 .setLastName("Firestone")

        // invoke activity call
        do {
            try Breinify.activity(breinUser,
                    activityType: "paginaUno",
                    category: "home",
                    description: "paginaUno-Description",
                    success: successBlock,
                    failure: failureBlock)
        } catch {
            dump("Error is: \(error)")
        }
    }

   override func viewDidLoad() {
    super.viewDidLoad()

    // this has to be a valid api-key & secret
    let validApiKey = "772A-47D7-93A3-4EA9-9D73-85B9-479B-16C6"
    let validSecret = "lmcoj4k27hbbszzyiqamhg=="

    // create the configuration object
    let breinConfig = BreinConfig(apiKey: validApiKey, secret: validSecret)
    
    // set configuration
    Breinify.setConfig(breinConfig)    
   }
}

Additional Code Snippets

The following code snippets provides addtional information how to use the BreinifyApi library for iOS.

BreinUser

Class BreinUser provides additional methods to add further data. This example shows all possible options:

let breinUser = BreinUser(email: "user.anywhere@email.com")

breinUser.setFirstName("User")
         .setLastName("Anywhere")
         .setImei("356938035643809")
         .setDateOfBirth(6, day: 20, year: 1985)
         .setDeviceId("AAAAAAAAA-BBBB-CCCC-1111-222222220000")
         .setSessionId("SID:ANON:w3.org:j6oAOxCWZh/CD723LGeXlf-01:034")
         .set