Classes


GranifyInlineView

Declaration:

@objc(GFYGranifyInlineView)
public class GranifyInlineView : UIView

A view that an inline campaign can be displayed into. Handlers to expand and collapse the view must be passed in so that inline views can be displayed. A GranifyInlineViewLabel must be provided.

Since: 6.0.0

See more

Properties

label 

A label that defines identifying information for this view.

Declaration:

@objc
dynamic public var label: GranifyInlineViewLabel? { get set }

Methods

init(label:expandHandler:collapseHandler:)

Initialization function used when this object is created programmatically, rather than by a storyboard.

Declaration:

public init(
label: GranifyInlineViewLabel,
expandHandler: @escaping GranifyInlineViewExpander,
collapseHandler: @escaping GranifyInlineViewCollapser
)

init(coder:)

Initialization function used when this object is created by a storyboard. When using this initializer, setExpandHandler, setCollapseHandler, and setLabel must be called later.

Declaration:

required public init?(coder: NSCoder)

setExpandHandler(expandHandler:) Since 6.0.0

Registers a handler that is used to expand the GranifyInlineView. Expect this handler to be invoked before an inline campaign is displayed. TheGranifyInlineViewwill expand and the inline campaign will be displayed inside of it. The Contextual Commerce SDK handles animation of the inlines internally.

Refer to the Implement inline campaigns topic for details on setting up your GranifyInlineView.

Declaration:

public func setExpandHandler(expandHandler: @escaping GranifyInlineViewExpander)

Parameters:

expandHandler A handler that expands the GranifyInlineView.
setCollapseHandler(collapseHandler:) Since 6.0.0

Registers a handler that is used to collapse the GranifyInlineView so it is no longer visible. Expect this handler to be invoked anytime the GranifyInlineView is no longer needed to display. The Contextual Commerce SDK handles animation of the inlines internally.

Declaration:

public func setCollapseHandler(collapseHandler: @escaping GranifyInlineViewCollapser)

Parameters:

collapseHandler A handler that collapses the GranifyInlineView.
setLabel(label:) Since 6.0.0

Attaches a GranifyInlineViewLabel, used by the Contextual Commerce SDK for GranifyInlineView identification. Whenever the contents of the superview of a GranifyInlineView are changed such that its GranifyInlineViewLabel is no longer reflective of the superview’s contents (e.g. new product id, sku), this should be called to update the GranifyInlineView‘s GranifyInlineViewLabel.

Declaration:

public func setLabel(label: GranifyInlineViewLabel)

Parameters:

label A GranifyInlineViewLabel describing this GranifyInlineView.
removeFromSuperview() Since 6.1.0

Unlinks the view from its superview and its window, and removes it from the responder chain. This method is called automatically, and should not be called directly.

Declaration:

public override func removeFromSuperview()
didMoveToWindow()

Tells the view that its window object changed. This method is called automatically, and should not be called directly.

Declaration:

public override func didMoveToWindow()

GranifyInlineViewLabel

Declaration:

@objc(GFYGranifyInlineViewLabel)
public class GranifyInlineViewLabel : NSObject

A label that defines identifying information for a GranifyInlineView.

Since: 6.0.0

See more

Properties

name

Unique string identifier for the associated GranifyInlineView.

Declaration:

public let name: String
productId

The ID of the associated product. Required when the associated GranifyInlineView is unique to a specific product. For example, any GranifyInlineView on a product page must have the productId included in the label.

Declaration:

public let productId: String?
sku

The SKU of the associated product. Required only when the associated GranifyInlineView is unique to a specific productID/SKU combination.

Declaration:

public let sku: String?

Methods

init(name:productId:sku:)

Initialization function.

Declaration:

@objc
public init(name: String, productId: String? = nil, sku: String? = nil)

Parameters:

name Required field. Identifies the associated GranifyInlineView. This field must be unique per location on a parent view.
productId The ID of the associated product. Required when the GranifyInlineView is located on a product page, or on any page where it is associated with a specific product (ie. inlines associated with a cart product).
sku Field that is required when the associated GranifyInlineView is associated with a specific productID/SKU combination.
isEqual(_:)

Returns a Boolean value that indicates whether the receiver and a given object are equal.

Declaration:

override public func isEqual(_ object: Any?) -> Bool

Parameters:

object The object to be compared to the receiver. May be nil, in which case this method returns false.
matchesHash(hash:)

Evaluates if a [String: String] hash matches the label.

Declaration:

public func matchesHash(hash: [String : String]) -> Bool

Parameters:

hash The hash to evaluate.

Granify

Declaration:

@objc(GFYGranify)
public class Granify : NSObject

The entry point for all Contextual Commerce SDK API methods. All methods on the API are exposed as class functions on this class.

Example: Granify.activateGranify(...)

See more

Methods

activateGranify(with:)

Activates the Contextual Commerce SDK and initiates communication with Contextual Commerce servers. This function must be called on app launch before any other method on this API (excepting subscription and registration methods) to allow the SDK to intialize itself with the provided site information.

See the Activate SDK article for details on how to prepare the GranifyConfigurationobject.

When to call:

Call this method once when the app starts, before it renders the first page. Register all providers and subscribe to all events before you call this method.

Declaration:

@objc
public class func activateGranify(with config: GranifyConfiguration) throws

Parameters:

config The GranifyConfiguration object which contains all SDK configuration.
subscribeGroupAssigned(handler:) 

Registers a callback to notify you when a matching group has been assigned.

In most cases, this handler is expected to send the group assignment information to your analytics. This group assignment metric tracks whether the current shopper is eligible to be shown a message (“Granify” group), or not (“baseline” group). Expect your handler to be invoked by Granify on startup, and when a new session is started (eg: after a lengthy period of inactivity).

Placement:

Call this function once, immediately before activateGranify(...), to register a handler before group assignment.

Usage:

The group that your handler receives when invoked is the exact group that should be reported in your analytics.

No changes are permitted on the group when reporting in your analytics.

Declaration:

@objc
public class func subscribeGroupAssigned(handler: @escaping (MatchingGroup) -> Void)

Parameters:

handler The function to be called for notification of a matching group assignment.
subscribeMessageShown(handler:)

Registers a callback to notify you when a message is (or could have been) shown.

In most cases, this handler is expected to send the display status information to your analytics. The message shown metric tracks when our engine decides to show a message to a shopper. Messages may beshownornotShowndepending on the shopper’s group assignment (granifyvs.baseline, respectively).

Expect your handler to be invoked by Granify at any time, when our engine decides to show a message to a shopper.

Your handler will be invoked on the main process thread.

Placement:

Call this method once, immediately before activateGranify(...), to register a handler before messages appear.

Declaration:

@objc
public class func subscribeMessageShown(handler: @escaping (DisplayStatus) -> Void)

Parameters:

handler The function to be called for notification of a message display.
registerGroupAssignment(provider:)

Register a handler for providing group assignments when a new session is created.

In most cases, Contextual Commerce controls matching group assignments, but arrangements can be made with Contextual Commerce to control group assignments via this handler instead. Allowed group values for your site may be a subset of those in the MatchingGroup enumeration, so work with your Account Manager to determine how to use this function for your specific needs.

Expect your handler to be invoked by Granify any time a request is made that may result in a new session. This will happen after the first trackPageView(...)request is made (starting traffic to the server) and at arbitrary later points when starting a new session after expiry.

Note that an invocation of this callback does not necessarily indicate that a new session will start. In some cases, the SDK may expect the session to be expired even though it is still active on the server. For example, rebooting the application will clear all local state causing the SDK to assume a new session is needed (thereby invoking this handler) even though the server can recover the existing session for the shopper. UsesubscribeGroupAssigned(...)for reliable notifications of group assignments for new sessions.

Placement:

When in use, this function must be called prior toactivateGranify(...)on application launch.

Declaration:

@objc
public class func registerGroupAssignment(provider: @escaping () -> MatchingGroup) throws

Parameters:

provider The callback function that provides the MatchingGroup for the session being initialized.
setShopperId(shopperId:)

Notifies Contextual Commerce of the current customer’s unique identifier.

This should be the same identifier you use in your store for your customers. It should not change if the same customer returns. If the shopper cannot be uniquely identified, this function should not be called.

Do not use email addresses for shopper IDs.

Placement:

Call this method once, immediately after you activate Granify. If the shopper's identifier is not immediately available (for example, while waiting for a server response or sign-in), call the method as soon as the identifier is known. This usually occurs on application launch or after the shopper signs in.

Declaration:

@objc
public class func setShopperId(shopperId: String) throws

Parameters:

shopperId The unique identifier for the customer from your internal systems. This should remain the same for the customer on subsequent returns.
clearShopperId()

Clears the current shopper identifier.

Placement:

This function should be called whenever the current shopper identifier is no longer applicable, such as user log-out.

Declaration:

@objc
public class func clearShopperId() throws
setChildSiteId(childSiteId:)

Notifies Contextual Commerce that the child site has changed.

In cases where a client has an app that uses multiple child sites (multiple brands), use this method when the shopper switches from one brand to another.

Multiple brands in one app information 

Use this method when the shopper switches between brands in a multi-brand app. 

  • ID configuration: Contextual Commerce provides a parent Site ID and separate Child Site IDs for each brand. If you have a single brand, pass nil for the Child Site ID.
  • Set the parent Site ID and the initial Child Site ID in the GranifyConfiguration object when you activate Granify. You cannot change the parent Site ID during a session.
  • Switching brands: Call Granify.setChildSiteId(...) whenever the active brand changes. The system maintains the current brand until you call this method again. If a user switches brands for a single page and returns, call the method twice (once for the new brand, once to revert).
  • Products: Every Product object includes a Product.childSiteOwnerId property. Ensure this property matches the active brand when you create the Product object.


Placement:

This function should be called as soon as the child site (brand) in the app changes from the child site initially set in configuration, as well as any subsequent changes. If the brand changes because a new page is loaded, call this method immediately after theGranify.trackPageView(...)method, beforeGranify.trackProduct(...)or any other Granify call.

Declaration:

@objc
public class func setChildSiteId(childSiteId: SiteIdentifier?) throws

Parameters:

childSiteId The site identifier for the child site. This should be Granify’s identifier, which will be provided to you.
trackPageView(pageType:parentView:mainScrollView:getInsets:) (Deprecated)

Tracks any changes to the active “page” or view that is displayed to the user in the application.

It is important to keep Contextual Commerce notified about the current page and the shopper’s navigation through the app so our engine can make appropriate decisions about what messages should be shown to which shoppers for maximum impact. This includes tracking what the user is currently viewing on the page via the use of scroll distance metrics. In UIKit, these metrics are inferred from the main UIScrollView for the page; however, in SwiftUI these scroll metrics are tracked differently.

Deprecated. Use:trackPageView(pageIdentifier: PageIdentifier, parentView: UIView?, mainScrollView: UIScrollView?, getInsets: () -> UIEdgeInsets)

See Track page views for more information. 

Placement:

This function should be called:

  • On application launch
  • On application resume from background
  • Each time a page navigation occurs (ensure to place it inside theviewDidAppear()View Controller callback)

Declaration:

@available(*, deprecated, message: "Use: trackPageView(pageIdentifier: PageIdentifier, mainScrollView: UIScrollView?, getInsets: (﹚ -> UIEdgeInsets﹚")
@objc
public class func trackPageView(pageType: PageType, parentView: UIView? = nil, mainScrollView: UIScrollView? = nil, getInsets: @escaping () -> UIEdgeInsets) throws

Parameters:

pageType The page type of the current page.
mainScrollView (UIKit Only) The main UIScrollView object of the current page (if the page is scrollable). Since 2.0.0
getInsets A callback method that returns the insets within which a slider can be displayed. When called, provide insets from the screen edges representing areas that must not be occluded for the current page layout and orientation. Since 4.0.0
parentView (UIKit Only) The superview containing all the subviews on the current UIKit page.This parameter must be passed in if inlines are desired to be displayed on that page. Since 6.0.0
trackPageView(pageIdentifier:parentView:mainScrollView:getInsets:) Since 6.2.0

Tracks any changes to the active “page” or view that is displayed to the user in the application.

It is important to keep Contextual Commerce notified about the current page and the shopper’s navigation through the app so our engine can make appropriate decisions about what messages should be shown to which shoppers for maximum impact. This includes tracking what the user is currently viewing on the page via the use of scroll distance metrics. In UIKit, these metrics are inferred from the main UIScrollView for the page; however, in SwiftUI these scroll metrics are tracked differently.

See Track page views for more information. 

Placement:

Call this method whenever a page opens (including the first page) and when the app resumes, to ensure the session remains active. Call this method:

  • On application launch
  • On application resume from background
  • Each time a page navigation occurs (inside theviewDidAppear()View Controller callback)

Declaration:

@objc
public class func trackPageView(pageIdentifier: PageIdentifier, parentView: UIView? = nil, mainScrollView: UIScrollView? = nil, getInsets: @escaping () -> UIEdgeInsets) throws

Parameters:

pageIdentifier Contains information about the page’s type and unique path.
mainScrollView (UIKit Only) The main UIScrollView object of the current page (if the page is scrollable).
getInsets A callback method that returns the insets within which a slider can be displayed.When called, provide insets from the screen edges representing areas that must not be occluded for the current page layout and orientation.
parentView (UIKit Only) The superview containing all the subviews on the current UIKit page.This parameter must be passed in if inlines are desired to be displayed on that page. This parameter must be omitted for SwiftUI.
trackProduct(products:currentProductCarterCallback:) 

Notifies Contextual Commerce about the products available on a product page.

Supplied product information is cached in memory and may be used for the display of messages at a later point in time. All product variations (i.e. skus) on a page must be provided. For example, if a shirt has different colors and sizes, the product list provided must include an entry for every combination of shirt color and size.

See Track Product for more details.

Placement:

This function must be called immediately after trackPageView(...)and whenever the selected product SKU changes (including the initial selection). Call this method with the current SKU in the following scenarios: 

  • On application launch to a product page (for example, via deep linking)
  • On application resume from background (when resuming to a product page)
  • After navigating to a product page
  • When the user selects a new variant

Declaration:

@objc
public class func trackProduct(products: [Product], currentProductCarterCallback: @escaping CurrentProductCarterCallback) throws

Parameters:

products The list of all products featured on the product page.
currentProductCarterCallback A handler that adds the current product to the cart.
setCurrentProduct(sku:productId:) 

Notifies Contextual Commerce which specific product on a product page is currently selected.

See Track Product for more details.

Placement:

This function must be called immediately aftertrackProduct(...), and when the focused item is changed on a product page. This includes:

  • On application launch to a product page (call with the default selected product sku)
  • On application resume from background to a product page (call with the selected product sku when the view loads)
  • From a navigation action leading to a product page (call with the default selected product sku)
  • User action that changes the selected product sku on a product page

Declaration:

@objc
public class func setCurrentProduct(sku: String, productId: String) throws

Parameters:

sku The SKU of the currently selected product.
productId The parent ID of the product.
trackCart(items:) 

Notifies Contextual Commerce of the contents of the shopper’s cart.

All cart information is required (rather than partial changesets) to sync the customer’s cart with Contextual Commerce. Ensuring that this is kept up to date is crucial to ensure cart-related campaigns work.

See Track Product for more details.

Placement:

Call trackCart immediately after activateGranify when the app starts. Call trackCart again whenever the app resumes or the cart changes. Common triggers include:

  • On initial app launch
  • After there is any change made to the cart. This includes:
    • After a purchase is completed (to clear the cart), including through the use of a “Buy It Now” or other express purchase button
    • Item removal
    • Cart item quantity changes
    • Updated cart information from a server response (e.g. from shopping performed on the same user account on a different device)
This method should never be called in the same session withtrackCartChange. The two methods are intended for mutually exclusive circumstances; you should never need to call both in the same app.   
Which Cart Tracking Method Should I Use? 

Most applications have full access to cart contents, either managing them directly or synchronizing with a cloud version. In these scenarios, use trackCart to send cart details to Contextual Commerce. This is the preferred method.

However, some applications separate the shopper journey. One component might manage products and categories without cart access, while another handles the cart and checkout without access to the product catalog.

For example, a native iOS application might render the product catalog, while a website in a webview handles the cart and checkout. In this scenario, the native application lacks access to the cart but might add products using an API call. To notify Contextual Commerce of a cart change in this scenario, use the trackCartChange method.

Declaration:

@objc
public class func trackCart(items: [Product : Int]) throws

Parameters:

items A dictionary containing carted products as keys and corresponding cart quantities as values.
trackCartChange(add:quantity:) Since 5.5.0

Notifies Contextual Commerce that an item has been added to the cart, or that the quantity of an item already in the cart has been increased.

This method requires only information about the change itself. It does not require the complete cart details.

See Track Product for more details.

Placement:

Call trackCartChange immediately when a change occurs in the cart. Do not call this method on app launch. Call this method when:

  • A new item is added

  • An item is removed

  • An item's quantity changes

This method should never be called in the same session withtrackCart. The two methods are intended for mutually exclusive circumstances; you should never need to call both in the same app.
Which Cart Tracking Method Should I Use? 

Declaration:

@objc
public class func trackCartChange(add product: Product, quantity: Int) throws

Parameters:

add A Product object representing the whole product being added / incremented. This method does not differentiate between adding and incrementing, so we always require the whole product.
quantity The number of items to add to the cart.This should describe the change, and not the final amount in the cart. So, if the cart already has 3 items, and this method is called with a quantity of 2, the cart will end up with a quantity of 5.
trackCartChange(remove:quantity:) Since 5.5.0

Notifies Contextual Commerce that an item has been removed from the cart, or that the quantity of an item already in the cart has been decreased.

This method requires only information about the change itself. It does not require the complete cart details.

See Track Product for more details.

Placement:

Call trackCartChange immediately when a change occurs in the cart. Do not call this method on app launch. Call this method when:

  • A new item is added

  • An item is removed

  • An item's quantity changes

This method should never be called in the same session withtrackCart. The two methods are intended for mutually exclusive circumstances; you should never need to call both in the same app.

Which Cart Tracking Method Should I Use? 

Most applications have full access to cart contents, either managing them directly or synchronizing with a cloud version. In these scenarios, use trackCart to send cart details to Contextual Commerce. This is the preferred method.

However, some applications separate the shopper journey. One component might manage products and categories without cart access, while another handles the cart and checkout without access to the product catalog.

For example, a native iOS application might render the product catalog, while a website in a webview handles the cart and checkout. In this scenario, the native application lacks access to the cart but might add products using an API call. To notify Contextual Commerce of a cart change in this scenario, use the trackCartChange method.

Declaration:

@objc
public class func trackCartChange(remove sku: String, quantity: Int) throws

Parameters:

remove The sku of the product in the cart.
quantity The number of items to remove from the cart. This should describe the change, and not the final amount in the cart. So, if the cart already has 3 items, and this method is called with a quantity of 2, the cart will end up with a quantity of 1. If this value is greater than or equal to the current quantity in the cart, the item will be removed completely. If you do not know how many items are currently in the cart, use a very high number that you are sure is more than the quantity in the cart.
trackOrder(details:) 

Notifies Contextual Commerce about completed purchases.

Placement:

Call this method only after an order is finalized and paid (for example, on the receipt page). Do not call this method when the checkout process starts. Ensure the data provided to Contextual Commerce matches your analytics data.

Declaration:

@objc
public class func trackOrder(details: Order) throws

Parameters:

details An object containing the details of the completed order.
trackWishList(name:contents:)

Notifies Contextual Commerce of the contents of the shopper’s wish list.

This method can be called multiple times for different lists you wish to track. Please ensure that you use a unique name for each list tracked (for example, “Saved for Later”or “Christmas”) per user.

Placement:

Call trackWishList immediately after activateGranify. Call this method once for each wish list the user has. If wish list data is unavailable (for example, before sign-in), call the method with an empty list.

Call trackWishList again with updated contents whenever:

  • The shopper signs in

  • Items are added, removed, or modified

  • A list is added or deleted (for deletions, send the list name with empty contents)

  • The app resumes (to sync changes from other devices)

  • Updated wish list information from a server response (e.g. from shopping performed on the same user account on a different device)

Declaration:

@objc
public class func trackWishList(name: String, contents: [WishListItem]) throws

Parameters:

name The name of the wish list being tracked.
contents The contents of the wish list.
trackUserData(userData:) Since 6.10.0

Notifies Contextual Commerce of any information you want to remember and persist for any user of the device on which it is running. It will persist across pages within the current user session.

Placement:

Call this method whenever the information about the user you’d like to store has changed.

Declaration:

@objc
public class func trackUserData(userData: String) throws

Parameters:

userData An escaped JSON string with key-value pairs to be tracked. Only Strings, Integers, Booleans, and Arrays of each of those three types are supported. Nested objects and null are not supported values. Keys must only include alphanumeric strings that are separated by underscores.
Example

Code
let exampleUserData = """ {\ \"example_string\": \"Example String\",\ \"example_bool\": true,\ \"example_int\": 1,\ \"example_string_array\":[\"example_1\",\"example_2\"],\ \"example_bool_array\":[true,false],\ \"example_int_array\":[1,2,3,4]\ }\ """ try Granify.trackUserData(userData: exampleUserData)

showConcept(conceptId:) Since 2.0.0

Requests that Contextual Commerce show a specified concept (which we now call a campaign) within this session.

Once requested the campaign will be shown at the next available opportunity. As concepts are designed with various limitation around their presentation, (e.g. only showing on a product page), the campaign may not appear immediately after this call is made.

This method is not intended for regular use and should not be called during regular customer shopping sessions. It is a business review tool that allows seeing what a given Granify campaign will look like within your application so that any desired changes can be requested of the Bazaarvoice team. Bazaarvoice strongly recommends creating an easy way for trusted users to trigger this function to simplify previewing and testing of new concepts as they become available.

The id strings used to request concepts, can be obtained through your Account Manager.

Refer to Show campaigns for more details.

Placement:

This function can be called:

  • Any time afteractivateGranify(...)has been called

Declaration:

@objc
public class func showConcept(conceptId: String) throws

Parameters:

conceptId The id of the concept to display.
setRestrictionState(to:) Since 4.0.0

Tells Contextual Commerce to enter/exit a restricted state, during which no campaign can appear to the shopper. Note that this does not apply to inline campaigns, which willnotbe hidden while in a restricted state.

If your app has other popups, modals, or there are any times when you do not want a campaign to pop up, you can set the restricted state. When this state is on (.restricted), no campaigns will be shown. Switch it off to resume normal programming.

For example, if you have a promotional message that pops up when a shopper logs in, you might set the restricted state on while that popup is open, and then set if off again once the popup has been removed.

Please remember to always switch the restricted state off when you no longer require it.

The initial state of the SDK is RestrictionState.unrestricted upon activation.

Placement:

This function should be called:

  • when entering a situation where a campaign should not be shown
  • when exiting a situation where a campaign should not be shown

Declaration:

@objc
public class func setRestrictionState(to restrictionState: RestrictionState) throws

Parameters:

restrictionState a RestrictionState value indicating whether a campaign can be shown.
getCurrentState() Since 5.1.0

Generates an executable JavaScript script that will pass the current Contextual Commerce state to an embedded webview that is running a page that uses the Granify JavaScript SDK.

If your app is a hybrid app, such that some of the app runs natively, and other parts run as web pages in webviews, it is necessary for Contextual Commerce to pass state from the app to the webview whenever the app passes control from the app to the webview.

In such a case, call this method to receive a JavaScript snippet that will pass the current app state into the JavaScript Contextual Commerce SDK running in the webview. This script should be executed before the JavaScript Contextual Commerce SDK makes its first request to the Contextual Commerce backend servers (which happens pretty soon after load). It is safe to load this script before the JavaScript Contextual Commerce SDK has loaded. We recommend passing the script as soon as the webview finishes loading.

The internal state of the App Contextual Commerce SDK changes with every product viewed, and the JavaScript Contextual Commerce SDK needs the most up-to-date state to operate optimally. This means that the state must be passed again every time a new page loads into the webview - once for each time the JavaScript SDK loads.

We do not currently support passing state from the webview to the app. We can only support one-way transitions. This is appropriate if the app hosts its cart and checkout in a webview, but everything else in the app.

Placement:

This function should be called:

  • when passing control from the app to a webview
  • must be called each time a new page loads inside the webview.

Declaration:

@objc
public class func getCurrentState() throws -> String
overrideGranifyInlineView(label:) Since 6.0.0

Specifies a GranifyInlineView location in which to display inline widgets for testing purposes.

Placement:

Call this function when a user has manually entered an override string into a debug menu.

Declaration:

@objc
public class func overrideGranifyInlineView(label: String) throws

Parameters:

label A JSON object specifying the details of a GranifyInlineViewLabel.

SdkLogger

Declaration:

@objc(GFYSdkLogger)
public class SdkLogger : NSObject

Not intended for public use; this class and its methods are exposed due to technical requirements but are not intended to be used externally. Do not interact with this class or its constituents.

See more

Methods

write(message:logLevel:source:)

Not intended for public use; this method is exposed due to technical requirements but is not intended to be used externally. Do not call or otherwise interact with this method.

Declaration:

public static func write(message: String, logLevel: LogLevel, source: LogSource)

DeepLink

Declaration:

@objc(GFYDeepLink)
public class DeepLink : NSObject

Represents a URL that is assigned to a PageTypePageType. This is used in order to facilitate navigation to certain areas of your application.

More information on deep links

Campaigns often redirect shoppers to different parts of the site. Most commonly, they link to the cart, but they can also link to special campaign pages.

When configuring Granify, provide an array of DeepLink objects to enable deep linking into specific PageTypes. Deep links use either URLs or link factories.

  • URL: Ensure the URL allows the Granify SDK to navigate to the selected page type via universal links.

  • Link factory: A link factory is a closure that accepts parameters and executes the link. The closure handles navigation using the appropriate method for your app. It does not return a URL.

Granify calls the factory with parameters based on the PageType (for example, a .product page includes productId and sku).

For a list of types of pages we support, refer to Tracking Pages.

Code
let deepLinks = [
  DeepLink(pageType: .cart, link: URL(string: "com.mycompany.MyApp://cart")!),
  DeepLink(pageType: .product, linkFactory: { (params) in
      // do something to launch this page type
  }),
  ... // add links to all relevant page types
]


See more

Type Aliases

DeepLinkFactory

A closure that accepts a set of parameters, and performs a navigation to the page of the relevant type. A different set of parameters will be passed for each page type, depending on what is most appropriate for that page type. Most page types will receive an empty set of parameters, but.productpages, for example, will receive two parameters:productIdandsku. Note that the closure should not return aURL- it is the responsibility of the closure to perform the navigation itself.

Declaration:

public typealias DeepLinkFactory = ([String : String]) -> Void

Properties

pageType Since 2.0.0

The page type you are wanting to deep link to.

Declaration:

@objc
public let pageType: PageType
link Since 2.0.0

The URL used to deep link. eg com.mycompany.MyApp://cart.

Declaration:

@objc
public let link: URL?
linkFactory Since 5.3.0

A closure that performs the deep link. Accepts a collection of parameters, and allows the caller to decide exactly how the navigation should occur.

Declaration:

@objc
public let linkFactory: DeepLinkFactory?
description

Retrieves String representation of DeepLink.

Declaration:

public override var description: String { get }

Methods

init(pageType:link:linkFactory:)

Creates a DeepLink instance. Must pass either link or linkFactory. If both are passed, the factory will take precedence.

Declaration:

@objc
public init(pageType: PageType, link: URL? = nil, linkFactory: DeepLinkFactory? = nil)

Parameters:

pageType The page type you are wanting to deep link to.
link The URL used to deep link. eg com.mycompany.MyApp://cart.
linkFactory A closure that performs the deep link. Accepts a collection of parameters, and allows the caller to decide exactly how the navigation should occur.

DiscountCode

Declaration:

@objc(GFYDiscountCode)
public class DiscountCode : NSObject, Encodable

Represents an order discount code.

See more

Properties

code

The discount code string. Typically this is some coupon or promo code string entered by the user to apply the discount to the order.

Declaration:

@objc
public let code: String
amount

The discounted amount.

Declaration:

@objc
public let amount: Price

Methods

init(code:amount:)

Creates a DiscountCode instance.

Declaration:

@objc
public init(code: String, amount: Price)

Parameters:

code The discount code string.
amount The discounted amount.

GranifyConfiguration

Declaration:

@objc(GFYGranifyConfiguration)
public class GranifyConfiguration : NSObject

The general configuration object used to gather all info to activate  Contextual Commerce. 

This object will tell Contextual Commerce who you are (with forSite and optionally clientSiteId), and how we should navigate to various parts of your app. Many messages will need to direct the shopper to a different part of the app, particularly to specific product pages, but also to cart or even informational pages. This is how you tell Contextual Commerce how to do that within your app.

For more information, refer to the Prepare the SDK for data validation topic.

See more

Type Aliases

ProductLinkBuilderCallback Since 2.0.0

A block to build a deep link URL directly to a product or sku. The block takes two arguments:

1. The id of product item to link to
2. Optionally, the specific sku, of that product, to link directly to, if applicable/possible

No guarantees are made about which thread may invoke your provided callback. The main process thread or a different worker thread may be used.

Declaration:

public typealias ProductLinkBuilderCallback = (String, String?) -> URL?

Methods

init(forSite:childSiteId:codeVersion:deepLinks:) Since 5.3.0

Creates a GranifyConfiguration instance.

Declaration:

@objc
public init(forSite siteId: SiteIdentifier,
childSiteId: SiteIdentifier? = nil,
codeVersion: String? = nil,
deepLinks: [DeepLink] = [])

Parameters:

siteId The 5-character (alpha-numeric, case sensitive) site identifier provided to you by your account manager.
childSiteId The 5-character (alpha-numeric, case sensitive) site identifier for the child site. This should benilin most cases. The exceptions are installs with parent and child sites; usually when a shared top-level domain across stores exists.
codeVersion The version string of your application code.
deepLinks An Array of DeepLink objects used to navigate within your app programmatically.
init(forSite:childSiteId:codeVersion:deepLinks:productLinkBuilder:)

Creates a GranifyConfiguration instance.

Declaration:

@available(*, deprecated, message: "Do not pass a productLinkBuilder; provide a DeepLink with a linkFactory instead.")
@objc
public convenience init(forSite siteId: SiteIdentifier,
childSiteId: SiteIdentifier? = nil,
codeVersion: String? = nil,
deepLinks: [DeepLink] = [],
productLinkBuilder: ProductLinkBuilderCallback? = nil)

Parameters:

siteId The 5-character (alpha-numeric, case sensitive) site identifier provided to you by your account manager.
childSiteId The 5-character (alpha-numeric, case sensitive) site identifier for the child site. This should benilin most cases. The exceptions are installs with parent and child sites; usually when a shared top-level domain across stores exists.
deepLinks An Array of DeepLink objects used to navigate within your app programmatically.
productLinkBuilder A block to build a deep link URL directly to a product or sku. Granify SDK strongly holds the provided block. Since 2.0.0
description

Retrieves String representation of GranifyConfiguration.

Declaration:

public override var description: String { get }

Order

Declaration:

@objc(GFYOrder)
public class Order : NSObject

Represents an order placed on the site.

See more

Properties

orderNumber

The unique identifier for this order.

Declaration:

@objc
public let orderNumber: String
currency

The local currency used for prices. Must be “USD”, unless another currency has been agreed upon by Bazaarvoice. 

Declaration:

@objc
public let currency: Currency
lineItemsTotal

The total value of all items in the cart before any discounts, taxes and shipping, but after sale pricing.

Declaration:

@objc
public let lineItemsTotal: Price
subtotal

The total value of the items in the order after discounts but before shipping or taxes. This should match the order total you use in your own analytics.

Declaration:

@objc
public let subtotal: Price
totalTax

The total value of any taxes applied to this order.

Declaration:

@objc
public let totalTax: Price
totalShipping

The total value of any shipping costs applied to this order.

Declaration:

@objc
public let totalShipping: Price
total

The total price (after discounts) including shipping and possibly taxes.

Declaration:

@objc
public let total: Price
lineItems

The products in the order and their corresponding ordered quantities.

Declaration:

@objc
public let lineItems: [Product : Int]
itemCount

The total number of items in the order.

Declaration:

@objc
public var itemCount: Int { get }
discountCodes

A list of discounts applied to this order. If no discounts are applicable, this should be an empty array.

Declaration:

@objc
public let discountCodes: [DiscountCode]
financialStatus

The payment status of the order. This should always be "paid" unless you want to send information about fraud or cancelled orders.

Declaration:

@objc
public let financialStatus: String
defaultFinancialStatus

The default financial status value for an order.

Declaration:

@objc
public static let defaultFinancialStatus: String

Methods

init(orderNumber:currency:lineItemsTotal:subtotal:totalTax:totalShipping:total:lineItems:discountCodes:financialStatus:) (Deprecated)

Creates an Order instance with all the required order details.

Declaration:

@available(*, deprecated, message: "Do not pass financialStatus, it is now defaulted to 'paid'.")
@objc
public init(orderNumber: String,
currency: Currency = Currency.usd,
lineItemsTotal: Price,
subtotal: Price,
totalTax: Price,
totalShipping: Price,
total: Price,
lineItems: [Product: Int],
discountCodes: [DiscountCode],
financialStatus: String = defaultFinancialStatus)

Parameters:

orderNumber The unique identifier for this order.
currency The local currency used for prices.
lineItemsTotal The total value of all items in the cart before any discounts, taxes and shipping, but after sale pricing.
subtotal The total value of the items in the order after discounts but before shipping or taxes.
totalTax The total value of any taxes applied to this order.
totalShipping The total value of any shipping costs applied to this order.
total The total value (after discounts) including shipping and taxes.
lineItems The products in the order and their corresponding ordered quantities.
discountCodes A list of discounts applied to this order. If no discounts are applicable, this should be an empty array.
financialStatus The payment status of the order. Use the provided parameter default ("paid") unless you want to send information about fraud or cancelled orders.
init(orderNumber:currency:lineItemsTotal:subtotal:totalTax:totalShipping:total:lineItems:discountCodes:)

Creates an Order instance with all the required order details.

Declaration:

@objc
public init(orderNumber: String,
currency: Currency = Currency.usd,
lineItemsTotal: Price,
subtotal: Price,
totalTax: Price,
totalShipping: Price,
total: Price,
lineItems: [Product: Int],
discountCodes: [DiscountCode])

Parameters:

orderNumber The unique identifier for this order.
currency The local currency used for prices.
lineItemsTotal The total value of all items in the cart before any discounts, taxes and shipping, but after sale pricing.
subtotal The total value of the items in the order after discounts but before shipping or taxes.
totalTax The total value of any taxes applied to this order.
totalShipping The total value of any shipping costs applied to this order.
total The total value (after discounts) including shipping and taxes.
lineItems The products in the order and their corresponding ordered quantities.
discountCodes A list of discounts applied to this order. If no discounts are applicable, this should be an empty array.

PageIdentifier

Declaration:

@objc(GFYPageIdentifier)
public class PageIdentifier : NSObject

Contains information about a page’s type and its unique path.

See more

Properties

pageType

The PageType of the current page.

Declaration:

@objc
public let pageType: PageType
path

The unique path for the page.

Declaration:

@objc
public var path: String
hash

Returns an integer that can be used as a table address in a hash table structure.

Declaration:

public override var hash: Int { get }
description

A textual representation of the receiver.

Declaration:

public override var description: String { get }

Methods

init(pageType:path:)

Initializer.

Declaration:

@objc
public init(pageType: PageType, path: String = "")

Parameters:

pageType The PageType of the current page.
path The unique path for the page.
getIdentifyingURL()

Formats the pageIdentifier in a URL-like string.

Declaration:

@objc
public func getIdentifyingURL() -> String
updatePathIfEmpty(path:)

Sets the value of path, only if it has not previously been set.

Declaration:

public func updatePathIfEmpty(path: String)

Parameters:

path The unique path for the page.
isEqual(_:)

Returns a Boolean value that indicates whether the receiver and a given object are equal.

Declaration:

public override func isEqual(_ object: Any?) -> Bool

Parameters:

object The object to be compared to the receiver. May be nil, in which case this method returns false.

Price

Declaration:

@objc(GFYPrice)
public class Price : NSObject, Encodable

Represents a positive monetary price value.

See more

Properties

amount

The magnitude of the price to two decimal places.

Declaration:

@objc
public var amount: Decimal { get }
hash

Override for Hashable protocol implementation to hash based on numeric value.

Declaration:

public override var hash: Int { get }
description

Retrieves String representation of Price.

Declaration:

public override var description: String { get }

Methods

init(amount:)

Creates a Price instance. Returns nil if the provided amount cannot be represented (such as if it is negative).

Declaration:

@objc
public init?(amount: Decimal)

Parameters:

amount The magnitude of the price.
isEqual(_:)

Returns a Boolean value that indicates whether the receiver and a given object are equal. Equality for Price objects is assessed by comparing its numeric components.

Declaration:

public override func isEqual(_ object: Any?) -> Bool

Parameters:

object The object to be compared to the receiver.
encode(to:)

Encodes an instance of Price.

Declaration:

public func encode(to encoder: Encoder) throws

PrimitiveWrapper

Declaration:

@objc(GFYPrimitiveWrapper)
public class PrimitiveWrapper : NSObject, Encodable

Wrapper for primitive values (String, Int, Boolean or Decimal) for use in Product.customProperties. Holds a value of one type at a time.

See more

Properties

description

Retrieves String representation of PrimitiveWrapper.

Declaration:

override public var description: String { get }

Methods

init(stringValue:) Since 2.0.0

Creates a PrimitiveWrapper instance holding a String value.

Declaration:

@objc
public init(stringValue: String)

Parameters:

stringValue The String value to be stored.
init(intValue:) Since 2.0.0

Creates a PrimitiveWrapper instance holding an Int value.

Declaration:

@objc
public init(intValue: Int)

Parameters:

intValue The Int value to be stored.
init(boolValue:) Since 6.0.0

Creates a PrimitiveWrapper instance holding a Bool value.

Declaration:

@objc
public init(boolValue: Bool)

Parameters:

boolValue The Bool value to be stored.
init(decimalValue:) Since 6.0.0

Creates a PrimitiveWrapper instance holding a Decimal value.

Declaration:

@objc
public init(decimalValue: Decimal)

Parameters:

decimalValue The Decimal value to be stored.
encode(to:)

Encodes an instance of PrimitiveWrapper.

Declaration:

public func encode(to encoder: Encoder) throws

StringOrIntWrapper

Wrapper for StringorIntfor use inProduct.customProperties. Holds a value of either type, but not both. NOTE: this type has been deprecated in favour of the more usefulPrimitiveWrapper

Declaration:

@objc(GFYStringOrIntWrapper)
public class StringOrIntWrapper : NSObject, Encodable

Product

Declaration:

@objc(GFYProduct)
public class Product : NSObject, NSCopying, Encodable

Represents a distinct Product with basic identifiers, price, display information, and further optional detailed information.

See more

Properties

sku

The specific SKU of the product/variant.

Declaration:

@objc
public let sku: String
productId

The parent ID of the product.

Declaration:

@objc
public let productId: String
title

The name or title of the product.

Declaration:

@objc
public let title: String
price

The current unit price of the product (after discount or sale pricing).

Declaration:

@objc
public let price: Price
regularPrice

The regular price of the product before sales or discounts.

Declaration:

@objc
public let regularPrice: Price
image

The address of the product image.

Declaration:

@objc
public let image: URL
url

Deep link to app location.

Declaration:

@objc
public let url: URL
stock

The stock information for the product.

Declaration:

@objc
public let stock: ProductStock?
reviews

The review and rating information for the product.

Declaration:

@objc
public let reviews: ProductReviews?
category

The broad category containing this item.

Declaration:

@objc
public let category: String?
subCategory

Further categorical identification of item (optional).

Declaration:

@objc
public let subCategory: String?
color

The color of the SKU item (optional).

Declaration:

@objc
public let color: String?
size

The size of the SKU item (optional).

Declaration:

@objc
public let size: String?
customProperties

Named (keys) custom properties (values with a valid string representation) to be stored and reported to Contextual Commerce with the product. This is useful for adding additional properties that may be domain-specific to your site and do not fit into any of the existing properties available on this class.

Declaration:

@objc
public let customProperties: [String : PrimitiveWrapper]
childSiteOwnerId

The site id of the child site this product belongs to. Leave this nil unless your configuration uses child sites, in which case this value is required.

Declaration:

@objc
public let childSiteOwnerId: SiteIdentifier?
hash

Override for Hashable protocol implementation to make Productsrely only on the unique sku identifier.

Declaration:

override public var hash: Int { get }
description

Retrieves String representation of Product.

Declaration:

override public var description: String { get }

Methods

init(sku:productId:title:price:regularPrice:image:url:stock:reviews:category:subCategory:color:size:childSiteOwnerId:customProperties:)

Creates a Product instance.

Declaration:

@objc
public init(sku: String,
productId: String,
title: String,
price: Price,
regularPrice: Price,
image: URL,
url: URL,
stock: ProductStock? = nil,
reviews: ProductReviews? = nil,
category: String? = nil,
subCategory: String? = nil,
color: String? = nil,
size: String? = nil,
childSiteOwnerId: SiteIdentifier? = nil,
customProperties: [String: PrimitiveWrapper] = [:])

Parameters:

sku The specific SKU of the product/variant.
productId The parent ID of the product.
title The name or title of the product.
price The current unit price of the product (after discount or sale pricing).
regularPrice The regular price of the product before sales or discounts.
image The address of the product image.
url Deep link to app location.
stock The stock information for the product (optional).
reviews The review and rating information for the product (optional).
category The broad category containing this item (optional).
subCategory Further categorical identification of item (optional).
color The color of the SKU item (optional).
size The size of the SKU item (optional).
childSiteOwnerId The site id of the child site this product belongs to (optional).
customProperties Named (keys) custom properties (values with a valid string or integer representation) to be stored and reported to Contextual Commerce with the product. This is useful for adding additional properties that may be domain-specific to your application and do not fit into any of the existing properties available on this class.
copy(with:)

Returns a new instance that’s a copy of the receiver.

Required for conforming to NSCopying, which is required for using Product as an NSDictionary key when using Contextual Commerce from Objective-C.

Declaration:

public func copy(with zone: NSZone? = nil) -> Any

Parameters:

zone
This parameter is ignored. Memory zones are no longer used by Objective-C.

Return value:

New copiedProductinstance

isEqual(_:)

Returns a Boolean value that indicates whether the receiver and a given object are equal. Equality for Product objects is assessed by comparing only the unique sku identifiers.

Declaration:

override public func isEqual(_ object: Any?) -> Bool

Parameters:

object
The object to be compared to the receiver.

Return value:

trueif the receiver andobjectare equal, otherwisefalse

ProductReviews

Declaration:

@objc(GFYProductReviews)
public class ProductReviews : NSObject, Encodable

Contains product review and rating information.

See more

Properties

rating

The product rating rounded to two decimal places.

Declaration:

public var rating: Decimal? { get }
ratingScale

The allowable rating range.

Declaration:

public let ratingScale: ClosedRange?
reviewCount

The number of reviews.

Declaration:

public let reviewCount: UInt?
description

Retrieves String representation of ProductReviews.

Declaration:

public override var description: String { get }

Methods

init(rating:ratingScale:reviewCount:)

Creates a ProductReviews instance. Returns nil if all parameters are nil or if rating is out of range for the provided ratingScale.

Declaration:

public init?(rating: Double?,
ratingScale: ClosedRange?,
reviewCount: UInt?)

Parameters:

rating The product rating.
ratingScale The allowable rating range.
reviewCount The number of reviews.

StarRatedProductReviews

Declaration:

@objc(GFYStarRatedProductReviews)
public class StarRatedProductReviews : ProductReviews

Represents product reviews using a 1 to 5 star rating scale.

See more

Methods

init(stars:reviewCount:)

Creates a StarRatedProductReviews instance. Returns nil if stars is not between 1 and 5 (inclusive).

Declaration:

public init?(stars: Double?, reviewCount: UInt?)

Parameters:

stars The number of stars.
reviewCount The number of reviews.

PercentRatedProductReviews

Declaration:

@objc(GFYPercentRatedProductReviews)
public class PercentRatedProductReviews : ProductReviews

Represents product reviews using a 0 to 100 percentile rating scale.

See more

Methods

init(percentage:reviewCount:)

Creates a PercentRatedProductReviews instance. Returns nil if percentage is not between 0 and 100 (inclusive).

Declaration:

public init?(percentage: Double?, reviewCount: UInt?)

Parameters:

percentage The percentage rating value.
reviewCount The number of reviews.

ProductStock

Declaration:

@objc(GFYProductStock)
public class ProductStock : NSObject, Codable

Contains product stock information.

See more

Properties

count

The number of the product in stock.

Declaration:

@objc
public let count: Int
description

Retrieves String representation of ProductStock.

Declaration:

public override var description: String { get }

Methods

init(count:)

Creates a ProductStock instance.

Declaration:

@objc
public init(count: Int)

Parameters:

count The number of the product in stock.
inStock()

Queries whether the product is currently in stock. Returns true if the product stock count is greater than 0; false otherwise.

Declaration:

@objc 

public func inStock() -> Bool

Return value:

trueif the product stock count is greater than 0;falseotherwise

SiteIdentifier

Declaration:

@objc(GFYSiteIdentifier) 

public class SiteIdentifier : NSObject, Codable

Unique site identifier

This is a 5-character, case-sensitive, alphanumeric string provided to you by Bazaarvoice. 

See more

Methods

init(identifier:)

Creates aSiteIdentifier instance

Returns nil if identifier is not a 5-character alphanumeric string.

Declaration:

@objc
public init?(identifier: String)

Parameters:

>encode (to:)

Encodes an instance ofSiteIdentifier

Declaration:

public func encode(to encoder: Encoder) throws

Properties

description

RetrievesStringrepresentation ofSiteIdentifier

Declaration:

public override var description: String { get }

    
      
    
  
identifier

The underlyingStringsite identifier.

Declaration:

@objc
public let identifier: String​

    

WishListItem

Declaration:

@objc(GFYWishListItem)
public class WishListItem : NSObject, Encodable

Represents a product within a wish list.

See more

Properties

productId

The parent ID of the product.

Declaration:

@objc
public let productId: String
inStock

Whether the item is currently in stock.

Declaration:

@objc
public let inStock: Bool
sku

The specific SKU of the product/variant (optional).

Declaration:

@objc
public let sku: String?
price

The current unit price of the product, after discount or sale pricing (optional).

Declaration:

@objc
public let price: Price?
regularPrice

The regular price of the product before sales or discounts (optional).

Declaration:

@objc
public let regularPrice: Price?
title

The name or title of the product (optional).

Declaration:

@objc
public let title: String?
image

The address of the product image (optional).

Declaration:

@objc
public let image: URL?
dateAdded

The date when the product was added to the list (optional).

Declaration:

@objc
public let dateAdded: Date?
priceWhenAdded

The price of the product when it was added to the list (optional).

Declaration:

@objc
public let priceWhenAdded: Price?
callToAction

Address of the product’s anchor tag in the list page (optional).

Declaration:

@objc
public let callToAction: URL?
productPage

Address of the product page (optional).

Declaration:

@objc
public let productPage: URL?

Methods

init(productId:inStock:sku:price:regularPrice:title:image:dateAdded:priceWhenAdded:callToAction:productPage:)

Creates a WishListItem instance from each distinct item property.

Declaration:

@objc
public init(productId: String,
inStock: Bool,
sku: String? = nil,
price: Price? = nil,
regularPrice: Price? = nil,
title: String? = nil,
image: URL? = nil,
dateAdded: Date? = nil,
priceWhenAdded: Price? = nil,
callToAction: URL? = nil,
productPage: URL? = nil)

Parameters:

productId The parent ID of the product.
inStock Whether the item is currently in stock.
sku The specific SKU of the product/variant (optional).
price The current unit price of the product, after discount or sale pricing (optional).
regularPrice The regular price of the product before sales or discounts (optional).
title The name or title of the product (optional).
image The address of the product image (optional).
dateAdded The date when the product was added to the list (optional).
priceWhenAdded The price of the product when it was added to the list (optional).
callToAction Address of the product’s anchor tag in the list page (optional).
productPage Address of the product page (optional).
init(product:dateAdded:priceWhenAdded:callToAction:productPage:)

Creates a WishListItem instance from a Product and any additional (optional) property values.

Precondition:

The inStock property of the provided Product instance must be non-nil. nil will be returned if this condition is not met.

Declaration:

@objc
public convenience init?(product: Product,
dateAdded: Date? = nil,
priceWhenAdded: Price? = nil,
callToAction: URL? = nil,
productPage: URL? = nil)

Parameters:

product The product in the wish list.
dateAdded The date when the product was added to the list (optional).
priceWhenAdded The price of the product when it was added to the list (optional).
callToAction Address of the product’s anchor tag in the list page (optional).
productPage Address of the product page (optional).
encode(to:) Since 2.0.0

Encodes an instance of WishListItem.

Declaration:

public func encode(to encoder: Encoder) throws
Provide feedback button