Code Monkey home page Code Monkey logo

crobox-sdk-ios's Introduction

crobox-sdk-ios

Crobox SDK for iOS

Build Status Official Crobox project GitHub Release

This is an asynchronous SDK kit for consuming Crobox API for iOS applications, written in Swift.

First add the dependency to your project:

Installation

Swift Package Manager

// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    dependencies: [
        .package(url: "https://github.com/crobox/crobox-sdk-ios.git", from: "{{ latest_version }}"),
    ]
)

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Crobox into your Xcode project using CocoaPods, specify it in your Podfile:

 pod 'croboxSDK', '~> 1.0.31'

Start using Crobox SDK

First configure and create a Crobox singleton as:

Crobox.shared.initConfig(config: CroboxConfig(containerId: "xlhvci", visitorId: UUID.init(), localeCode: .en_US))

RequestQueryParams contains page specific parameters, shared by all requests sent from the same page/view. It must be recreated when the page/view is displayed.

let detailPageParams = RequestQueryParams.init(viewId: UUID(), pageType : .PageDetail, customProperties: ["test":"test"])

For sending events, use the xyzEvent APIs exposed by the Crobox instance. Events might also take event specific parameters:

var addCartQueryParams = CartQueryParams(productId: "abc")
addCartQueryParams.price = 2.0
addCartQueryParams.quantity = 3
Crobox.shared.addCartEvent(queryParams: detailPageParams, addCartQueryParams: addCartQueryParams)

For retrieving promotions for zero, one or more products, use the specific PlaceholderId that was already configured with specific page types and linked to campaigns via Crobox Admin App.

        let result = await Crobox.shared.promotions(placeholderId: "1",
                                                    queryParams: overviewPageParams,
                                                    productIds: ["1", "2", "3"])
        switch result {
        case let .success(p):
            print("id: \(p.promotions[2].id ?? "")")
            print("campaignId: \(String(describing: p.promotions[2].campaignId))")
            print("productId: \(p.promotions[2].productId ?? "")")
            print("variantId: \(p.promotions[2].variantId ?? -1)")
            print("content.id: \(p.promotions[2].content?.id ?? "")")
            print("content.config: \(p.promotions[2].content?.config?.data ?? [:])")
        case let .failure(error):
            print(error)
        }

Promotion Response Schema

        let result = await Crobox.shared.promotions(placeholderId: "1",
                                                    queryParams: overviewPageParams,
                                                    productIds: ["1", "2", "3"])
        switch result {
        case let .success(response):
            let context = response.context
            let promotions = response.promotions
            
            let visitorId = context.visitorId
            let sessionId = context.sessionId
            let groupName = context.groupName
            for campaign in context.campaigns {
                let campaignId = campaign.id
                let campaignName = campaign.name
                let variantId = campaign.variantId
                let variantName = campaign.variantName
                let control = campaign.control
            }
            for promotion in response.promotions {
                let promotionId = promotion.id
                let campaignId = promotion.campaignId
                let variantId = promotion.variantId
                let productId = promotion.productId
                if let content = promotion.content {
                    let messageId = content.messageId
                    let componentName = content.componentName
                    let configMap = content.config
                    for c in configMap {
                        let configKey = c.key
                        let configValue = c.value
                    }
                    let imageBadge = content.getImageBadge()
                    let textBadge = content.getTextBadge()
                               
                    let conf = p.content?.contentConfig()
                    switch conf {
                    case let conf as ImageBadge:
                        let image = conf.image
                        let altText = conf.altText
                    case let conf as TextBadge:
                        let text = conf.text
                        let fontColor = conf.fontColor ?? ""
                        let background = conf.backgroundColor ?? ""
                        let borderColor = conf.borderColor ?? ""
                    case let conf as SecondaryMessaging:
                        let text = conf.text
                        let fontColor = conf.fontColor ?? ""
                    default:
                        //
                    }
                }
            }
        
        case let .failure(error):
            print(error)
        }

PromotionsResponse

Name Type Description
context PromotionContext The context about campaigns
promotions List The list of promotions calculated

PromotionContext

Name Type Description
sessionId UUID Session ID
visitorId UUID Visitor ID
groupName String? The list of campaign and variant names, combined
campaigns List The list of ongoing campaigns

Campaign

Name Type Description
id String Campaign ID
name String Campaign Name
variantId String There is a ratio that determines the amount of traffic exposed to this campaign (or is allocated to the control group) between Crobox and Control group. Variant id refers to the variant which this promotion belongs to and is used for debugging
variantName String Name of the Campaign Variant
control Boolean Indicates if the variant is allocated to the control group

Promotion

Name Type Description
id String Unique id for this promotion
productId String? Product ID if requested
campaignId Int The campaign which this promotion belongs to
variantId Int ID of the variant that this promotion is assigned to
content PromotionContent? Promotion Content

PromotionContent

Name Type Description
messageId String As Campaigns might have alternative messages, Message Id identifies the message assigned to this promotion
component String Component Name
config Map<String, String> Map of all visual configuration items, managed via Crobox Admin app.
Example:
Map("Text1_text" : "Best Seller", "Text1_color" : "#0e1111")
getTextBadge TextBadge? Returns a Text Badge if a text component exists with the following pre-defined keys: "text", "fontColor", "backgroundColor" and "borderColor"
getImageBadge ImageBadge? Returns an Image Badge if an image component exists with the following pre-defined keys: "image" and "altText"

TextBadge

Name Type Description
text String Text message
fontColor String Font color
backgroundColor String? Optional background color
borderColor String? Optional border color

ImageBadge

Name Type Description
image String Image url
altText String? Alternate text

Secondary Messaging

Name Type Description
text String Text message
fontColor String Font color

Samples

See test snippet for various samples

crobox-sdk-ios's People

Contributors

idrisyildiz7 avatar toztemel avatar

Watchers

Lucian avatar  avatar  avatar

crobox-sdk-ios's Issues

socket endpoint: Remove from Shopping Cart events

The following arguments are applicable for RemoveFromCart events( where t=rmcart ). They are all optional

"pi" : ProductId
"cat" : Category
"price" :  Price
"qty": Quantity

ProductId
Type: String
Description: Identifier of a product.
Example: pi=abcd-123

Category
Type: String
Description: Category of a product.
Example: cat=mens_shoes

Price
Type: Double
Description: Numeric digits separated by comma or dot
Example: price=123,456 or 123.456

Quantity
Type: Int
Description: Numeric integer indicating the number of products
Example: qty=2

Common query parameters list for both endpoints

The list of query parameters that are applicable for mobile clients are below. These are applicable for both socket and promotions endpoints. Further details of each parameter are at the bottom. :

// Mandatory
"cid": ContainerId
"e":  ViewCounter
"vid": ViewId
"pid": VisitorId  

// Optional 
"cc":  CurrencyCode
"lc" : LocaleCode
"uid" : UserId
"ts": Timestamp
"tz": Timezone
"pt" : PageType
"cp.xyz" : Custom Property xyz

User-Agent header for web

Container ID
Type: String
Description: This is the unique id of the client's Crobox Container. It is generated and assigned by Crobox. So, this can be an alphanumeric constant configuration item, set only once by the sdk user.
Example: cid="abc123"

VisitorId
Type: UUID
Description: This is a randomly generated id that identifies a visitor / user. It must be the same across the user session (or even longer when possible). It must be in either plain UUIDv4 or Base64 string format. For simplicity, just pick Base64 for saving bandwidth space.
UUID Example: vid=d4055206-fa5b-4eef-96c4-17e1c3a857fd
Base64 Example: vid=1AVSBvpbTu-WxBfhw6hX_Q

ViewId
Type: UUID
Description: This is a randomly generated id that identifies a unique page view. It is reused between various event and promotion requests while the user stays on the same page. Then, it is refreshed when a user goes to another page or reloads the same page. In other words, every socket or promotion request from the same view, should share the same ViewId. It must be in either plain UUID or Base64 string format. For simplicity, just pick Base64 for saving bandwidth space.
UUID Example: vid=d4055206-fa5b-4eef-96c4-17e1c3a857fd
Base64 Example: vid=1AVSBvpbTu-WxBfhw6hX_Q

ViewCounter
Type: Integer
Description: Monotonically increasing counter, starting from 0. It is incremented per request in the same view. For instance, when the user is viewing and performing some actions on the same page, multiple promotion requests and events are sent. Among all these requests sharing the same ViewId, the counter should start from 0 and increment. This helps us group events by the view, and also guarantees for the uniqueness of a request/event when combined with ContainerId, VisitorId and ViewId.(Think of network failures or unintentional retries for example).
Example: e=1

OPTIONAL PARAMETERS

LocaleCode
Type: String
Description: Locale code combination for the localization. It must be in {language}-{COUNTRY} format where

  • the language must be lowercase, two-letter form of ISO 639-1 language codes
  • the country must be uppercase, two-letter form of ISO 3166-1 Country codes
    Example: lc=en_US

CurrencyCode
Type: String
Description: Contains information about the valid currency. It must be uppercase, three-letter form of ISO 4217 currency codes. It is useful when there are more than one currency configured in the Crobox Container.
Example: cc=USD

UserId
Type: String
Description: It is an identifier provided by the client that allows coupling of crobox user profiles with the client's user profiles, if available.
Example: uid=abc123

Timestamp
Type: String
Description: Timestamp as the millis since epoch, encoded with Base36.
Example: ts=lu9znf91 (when timestamp is 1711554991093)

Timezone
Type: Integer
Description: Current timezone of the user / device
Example:tz=-4

PageType
Type: Integer
Description: One of the values in predefined list of types of pages of the whole e-commerce funnel
PageOther = 0
PageIndex = 1
PageOverview = 2
PageDetail = 3
PageCart = 4
PageCheckout = 5
PageComplete = 6
PageSearch = 7
Example: pt=0

Custom Property [xyz]
Type: String
Description: Custom Property freely defined by the developer, using the prefix 'cp.'. This way, additional properties can be forwarded to Crobox endpoints, for example to help identifying certain traits of a visitor
Example: cp.mobileUser=yes

User-Agent header
Description: This header is applicable for web clients but I wonder if it can be re-used for mobile clients as well, in order to distinguish between mobile devices / operating systems.

socket endpoint: Transaction events

The following arguments are applicable for click events( where t=transaction ). They are all optional

"tid" : TransactionId
"rev" : Revenue
"cpn" : Coupon
"aff" : Affiliation

** Transaction Id **
Type: String
Description: Transaction identifier
Example: tid=abc123

** Revenue **
Type: String
Description: A decimal number that specifies the total revenue or grand total associated with the transaction. This value may include shipping, tax costs, or other adjustments to total revenue that you want to include as part of your revenue calculations. Note: if revenue is not set, its value will be automatically calculated using the product quantity and price fields of all products in the same hit.
Example: tid=11.99

** Coupon **
Type: String
Description: Coupon code for discounts
Example: tid=abc123

** Affiliation **
Type: String
Description: The store or affiliation from which this transaction occurred
Example: tid=Google Store

socket endpoint: Error events

The following arguments are applicable for error events( where t=error ). They are all optional.

"tg" : Tag
"nm" : Name
"msg" : Message
"f" : File
"l" : Line
"dpr" : Device Pixel Ratio
"ul" : Device Language
"vp" : View Port size
"sr" : Screen Resolution Size

Tag
Type: String
Description: Free text for categorization of errors by the developer
Example: tg=promotionAction

Name
Type: String
Description: Free text for naming of errors by the developer
Example: nm=TypeError

Message
Type: String
Description: Free text for description of errors by the developer
Example: msg=Cannot read product properties

File
Type: String
Description: Free text for a file name, if specified
Example: f=SomeFile.txt

Line
Type: Int
Description: Simple numeric value to indicate the line number
Example: l=2

Device Pixel Ratio
Type: Double
Description: From https://stackoverflow.com/a/8785677

The device pixel ratio is the ratio between physical pixels and logical pixels. For instance, the iPhone 4 and iPhone 4S report a device pixel ratio of 2, because the physical linear resolution is double the logical linear resolution.
Physical resolution: 960 x 640
Logical resolution: 480 x 320
Example: dpr=2

Device Language
Type: String
Description: Device language in the form of [language]-[country], with 2 lowercase letters each. Technically, it can be different than the lc locale, for instance lc=en-CA&ul=en-us can be a valid combination of a device from Canada
Example: ul=en-us

View Port size
Type:String
Description: From https://stackoverflow.com/a/73927240

Your screen size is the number of pixels in the total width and height of your computer. The size of your viewport is the number of pixels in the browser window on your screen, so it is quite normal for the viewport to be smaller than the screen size.
Example: vp=1173x686

Screen Resolution Size
Type: String
Description: The whole screen size of the device
Example: sr=1440x900

socket endpoint: Add to Shopping Cart events

The following arguments are applicable for AddToCart events( where t=cart ). They are all optional

"pi" : ProductId
"cat" : Category
"price" :  Price
"qty": Quantity

ProductId
Type: String
Description: Identifier of a product.
Example: pi=abcd-123

Category
Type: String
Description: Category of a product.
Example: cat=mens_shoes

Price
Type: Double
Description: Numeric digits separated by comma or dot
Example: price=123,456 or 123.456

Quantity
Type: Int
Description: Numeric integer indicating the number of products
Example: qty=2

socket endpoint: Page View events

The following arguments are applicable for click events( where t=pageview ). They are all optional

"dt" : PageTitle
"st" : SearchTerms
"pi" : Event Product / Product Id
"lst": Event Product / Product List

"imp" : Event Impressions / Impressions

// Page Type Dependant Arguments

// if pt = 5 (Checkout Page)
"stp" : Checkout / Step

// if pt = 6(Transaction)
"tid" : Transaction Complete/ TransactionId
"rev" : Transaction Complete / Revenue

PageTitle
Type: String
Description: It is used to specify Page Title, if available
Example: dt=abc123

Search Terms
Type: String
Description: If the visitor used search functionality, this field is used to specify the search terms that led the user to the displayed page
Example: dt=abc123

Event Product / Product Id
Type: String
Description: Unique identifier of the product displayed, if available
Example: pi=abc123

Event Product / Product List
Type: String
Description: Comma-separated list of Product Identifiers. If ProductId (pi) is set, this is to specify the collection of products that accompanies the original product pi displayed on the screen.
Example: lst=def456,ghi789

Impressions
Type: Array of Impression Object
Description: It is used to specify the collection of impressions listed, for example on an overview page. Each item may have the following attributes:

  • pi: Product ID: Unique identifier of a product displayed
  • psp: Product Sale Price
  • qty: Quantity

Example: Two impressions(imp) with Product Id(pi) and quantity(qty)
imp[0].pi=88888&imp[0].qty=1&imp[1].pi=88888&imp[1].qty=1

// Page Type Dependant Arguments
Checkout / Step
Type : Int
Description = If pageType is Checkout (pt=5), this argument specifies the step in the checkout process
Example: pt=5&stp=1

// if pt = 6(Transaction)
"tid" : Transaction Complete/ TransactionId
"rev" : Transaction Complete / Revenue

Transaction Complete / TransactionId
Type : String
Description: If pageType is Transaction Complete (pt=6), this argument specifies the transactionId if available
Example: pt=6&tid=abc123

Transaction Complete / Revenue
Type : String
Description: If pageType is Transaction Complete (pt=6) and transactionId is available, this argument specifies the total revenue if available
Example: pt=6&tid=abc123&rev=100

socket endpoint: Custom events

The following arguments are applicable for click events( where t=event ). They are all optional

"nm" : Name
"promoId" : Promotion ID
"pi" : Product ID
"cat" : Category
"price" : Price
"qty" : Quantity

Name
Type: String
Description: Custom event name
Example: nm=banner-click

Promotion ID
Type: UUID
Description: Promotion identifier
Example: promoId=c97c02c0-1f5a-11ef-81c0-cd67b451d09e

Product ID
Type: String
Description: Identifier of a product.
Example: pi=abcd-123

Category
Type: String
Description: Category of a product.
Example: cat=mens_shoes

Price
Type: Double
Description: Numeric digits separated by comma or dot
Example: price=123,456 or 123.456

Quantity
Type: Int
Description: Numeric integer indicating the number of products
Example: qty=2

socket endpoint: Click Events

The following arguments are applicable for click events( where t=click ). They are all optional

"pi" : ProductId
"cat" : Category
"price" :  Price
"qty": Quantity

ProductId
Type: String
Description: Identifier of a product.
Example: pi=abcd-123

Category
Type: String
Description: Category of a product.
Example: cat=mens_shoes

Price
Type: Double
Description: Numeric digits separated by comma or dot
Example: price=123,456 or 123.456

Quantity
Type: Int
Description: Numeric integer indicating the number of products
Example: qty=2

promotion endpoint: Request / Response model

In addition to common query parameters, the following query argument and request parameters are applicable for /promotions endpoint

QUERY ARGUMENTS

"vpid" : Placeholder Id

Placeholder Id (Mandatory)
Type: Int
Description: Identifier of the placeholder. A Placeholder represents a predesignated point on the user interface, where the promotion will be located and displayed. Placeholders are linked with campaigns which has all promotion attributes, UI components, messages and time frame. These are all managed via the Crobox Admin application.
Example: vpid=1

REQUEST MODEL
Request Type: application/x-www-form-urlencoded
Description: The request body is an indexed-array of product Ids, where each product is queried for a promotion to be applied. Request body is optional because some promotions are not related to any product. (For example, promotions for index or checkout pages)
Example: 0=abc123&1=def456&2=ghi789

RESPONSE MODEL

case class PromotionsResponse(context: Option[ContextDto], promotions: Seq[PromotionDto])

case class ContextDto(pid: String, sid: Option[String], groupName: Option[String], experiments: Seq[ExperimentContextDto])

case class ExperimentContextDto(id: Int, name: String, variantId: Int, variantName: String, control: Boolean)

case class PromotionDto(
    id: UUID,
    productId: Option[String],
    campaignId: Int,
    experimentId: Int,
    variantId: Int,
    content: Option[PromotionContentDto]
)

case class PromotionContentDto(id: UUID, config: Map[String, String])

RESPONSE DESCRIPTION
case class PromotionsResponse(context: Option[ContextDto], promotions: Seq[PromotionDto])

context:
type: Optional ContextDto
description: All campaigns in the current context

promotions
type: array of PromotionDto'
description: Promotions calculated

case class ContextDto(pid: String, sid: Option[String], groupName: Option[String], experiments: Seq[ExperimentContextDto])

groupName:
type: Optional string
description: 'List of campaign and variant names, combined '

pid:
type: string (of type uuid)
description: Profile ID

sid:
type: Optional string (of uuid)
description: Session ID

experiments:
type: array of ExperimentContextDto's
description: List of ongoing campaigns

case class ExperimentContextDto(id: Int, name: String, variantId: Int, variantName: String, control: Boolean)
id:
type: integer
description: Campaign ID

name:
type: string
description: Name of the campaign

variantId:
type: integer
description: Id of the campaign - variant
variantName:
type: string
description: Name of the campaign - variant
control:
type: boolean
description: Indicates if variant is allocated to the control group.

case class PromotionDto(
    id: UUID,
    productId: Option[String],
    campaignId: Int,
    experimentId: Int,
    variantId: Int,
    content: Option[PromotionContentDto]
)

id:
type: string
description: UUID. Unique id for this promotion (e.g. promoId)
productId:
type: string
description: >-
Product ID that this promotion was requested for (needed for
overview requests)
experimentId:
type: integer
description: The campaign this promotions belongs to
variantId:
type: integer
description: The variant this promotions belongs to
parameters.[key]: // TODO : parameters will be DEPRECATED soon. Ignore this for now!
type: string
description: Additional parameters that are used for the trigger values (like {{trigger}} used for XX% discount

case class PromotionContentDto(id: UUID, config: Map[String, String])

id:
type: string
format: uuid
description: Message ID of this promotion
config.[key]:
type: string
description: Configuration of each individual configuration item

socket endpoint: Product events

The following arguments are applicable for click events( where t=product ). They are all optional

"pi" : ProductId
"rating" : Rating
"ratingCount" : Rating Count
"title" : Title
"images" :  Images
"url": Url

ProductId
Type: String
Description: Identifier of a product.
Example: pi=abcd-123

Rating
Type: Double
Description: Rating score
Example: rating=0.98

Rating Count
Type: Int
Description: Rating count
Example: ratingCount=99

Title
Type: String
Description: Product Title
Example: title=abc123

Images
Type: String
Description: Product images
Example: images=

Url
Type: String
Description: Product url
Example: url=

socket endpoint: Common query Parameters

In addition to common parameters ( #7 ), here is a common query parameter for socket endpoint only:

// Mandatory
EventType "t"

EventType
Type: String
Description: Specifies the type of the event. It must be one of following:
"click" = Click
"cart" = Add to Shopping Cart
"rmcart" = Remove from Shopping Cart
"transaction" = Transaction
"pageview" = PageView
"error" = Error
"event" = CustomEvent
"product" = Product
"pf" = ProductFinder
Example: t=click

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.