Mobile SDK end-of-life has been announced and scheduled for the end of 2023, in favor of updated and more streamlined app personalization using server-side APIs.
Basic Methods
Main method returning the shared instance of the Dynamic Yield SDK.
+ (DYApi *)getInstance;
Examples:
//Objective-C
DYApi* _DY = [DYApi getInstance];
//Swift
let _DY = DYApi.getInstance().getInstance();
Setting the delegate listener for Dynamic Yield.
-(BOOL)setDelegate:(id<DYDelegateProtocol>)delegate
Examples
//Objective-C
[[DYApi getInstance] setDelegate:self];
//Swift
DYApi.getInstance().setDelegate(self);
Sets the unique identifier in order to log data; returns Yes if the secret is not nil or empty.
- (BOOL)setSecretKey:(NSString *)secret;
Parameter- secret: String key obtained from the DY Admin Console
//Objective-C
[_DY setSecretKey:@"YOUR_SECRET_KEY"];
//Swift
DYApi.getInstance().setSecretKey("YOUR_SECRET_KEY ");
Sets the unique identifier in order to log data; returns Yes if the secret is not nil or empty.
-(BOOL)setSecretKey:(NSString* _Nonnull)secret completionHandler:(void (^_Nullable)(ExperimentsState))completionHandler;
Parameters
- secret: String key obtained from the DY Admin Console
- completionHandler: A runnable that is called with the results of the Dynamic Yield SDK initialization results (the same as the parameters for experimentReadyWithState). This can be used instead of implementing the listener method experimentsReadyWithState.
//Objective-C
[[DYApi getInstance] setSecretKey:@"123456789123456789" completionHandler:^(ExperimentsState state) {
if (state == DY_READY_NO_UPDATE_NEEDED || state == DY_READY_AND_UPDATED){
//start runnning experiments
}
}];
//Swift
DYApi.getInstance().setSecretKey("123456789123456789123456789") { (experimentsState) in
if (experimentsState == DY_READY_AND_UPDATED || experimentsState == DY_READY_NO_UPDATE_NEEDED){
//start running experiments
}
}
-(void)enableDeveloperLogs:(BOOL)enable;
Parameter- enable: True will enable the developer logs
//Objective C:
[[DYApi getInstance] enableDeveloperLogs:true];
//Swift:
DYApi.getInstance().enableDeveloperLogs(true);
DelegateProtocol
A delegate class for receiving information about DYApi state.
experimentsReadyWithState
Called when experiments have been updated and are ready to use, with detailed state.
-(void) experimentsReadyWithState:(ExperimentsState)state
Parameter
- state: An enum holding the state with the following possible values:
- DY_NOT_READY experiments are not ready to use
- DY_READY_LOCAL_CACHE experiments loaded from local cache
- DY_READY_AND_UPDATED experiments has been updated from the server and ready to use
- DY_READY_NO_UPDATE_NEEDED experiments loaded from local cache and no more update is needed
Example
//obj-c
-(void) experimentsReadyWithState: (ExperimentsState) state {
if (state == DY_READY_NO_UPDATE_NEEDED || state == DY_READY_AND_UPDATED) {
//..do something
}
}
//swift
func experimentsReady(with state: ExperimentsState) {
if (state == DY_READY_AND_UPDATED || state == DY_READY_NO_UPDATE_NEEDED) {
//.. do something
}
}
User Data
Expose the user affinity profile.
-(NSDictionary*)getUserAffinityProfile;
Example
//Objective-C
NSDictionary* userAffinityScore = [[DYApi getInstance] getUserAffinityProfile];
NSLog(@"UserAffinityScore: %@",[userAffinityScore description]);
//Swift
let userAffinity = DYApi.getInstance().getUserAffinityProfile();
print(userAffinity?.description as String!);
Expose the user affinity profile.
-(void)getUserAffinityProfileCompletionHandler:(void(^_Nonnull)(NSDictionary* _Nonnull affinityProfile))completionHandler;
Parameter
- completionHandler: A callback function with the data.
Example
//Objective-C
[[DYApi getInstance] getUserAffinityProfileCompletionHandler:^(NSDictionary * _Nonnull affinityProfile) {
//do something with the result
}];
//Swift
DYApi.getInstance().getUserAffinityProfileCompletionHandler { (affinityProfile) in
//do something with the result
}
Used to identify the user across platforms (e.g. web, iOS, CRM, email); returns Yes if identifiers is not null or empty. We recommend calling this method wherever the user enters their customer ID (e.g. checkout).
- (BOOL)identifyUser:(DYUserData*)userAttributes;
Parameter
- userAttributes: Object of class DYUserData, holds basic identification attributes about the user
Example
//Objective-C
DYUserData* user = [DYUserData create];
//SHA 256 hashed email of the plain text email in lower case
[user setEmail:@"18B258E9ADE091623DD829132E1E9D8B4A7F7D90ABEA194001C54341C3F27B79"];
[_DY identifyUser:user];
//Swift
let user = DYUserData.create();
user.email = "18B258E9ADE091623DD829132E1E9D8B4A7F7D90ABEA194001C54341C3F27B79";
DYApi.getInstance().identifyUser(user);
Return the user ID generated by Dynamic Yield.
-(NSString* _Nullable)getDYID;
Example
//Objective-C
NSString* userID = [[DYApi getInstance] getDYID];
//Swift
let userID = DYApi.getInstance().getDYID();
Requires SDK version 3.7.0
Return the user ID generated by Dynamic Yield.
-(void)getDYID:(void(^_Nonnull)(NSString* _Nonnull dyid))completionHandler;
Parameter
- completionHandler: A callback function with the data
Example
//Objective-C
[[DYApi getInstance] getDYID:^(NSString * _Nonnull dyid) {
//do something with the result
}];
//Swift
DYApi.getInstance().getDYID{(dyid) in
//do something with the result
};
Returns an array of audiences to which to user is assigned from the Dynamic Yield server, or Null if no audience is available.
- (NSArray*)getUserAudiences;
Example
//Objective-C
NSArray* audiences = [_DY getUserAudiences];
//Swift
let aud = DYApi.getInstance().getUserAudiences();
Requires SDK version 3.7.0
Returns an array of audiences to which to user is assigned from the Dynamic Yield server, or Null if no audience is available.
-(void)getUserAudiences:(void(^_Nonnull)(NSArray* _Nonnull audiences))completionHandler;
Parameter
completionHandler: a callback function with the dataExample
//Objective-C
[[DYApi getInstance] getUserAudiences:^(NSArray * _Nonnull audiences) {
//do something with the result
}];
//Swift
DYApi.getInstance().getUserAudiences{(audiences) in
//do something with the result
};
Indicates that a user has consented to allow Dynamic Yield to collect and use their personal data.
- Opting out prevents future data collection from the current device/browser from all sections of the account, across all domains. This method overrides any past opt-in methods.
- If the visitor had opted out in the past, opting in will allow data collection moving forward.
For more details, see Visitor Data Privacy Management (GDPR Support).
Example
//Objective-C
[[DYApi getInstance] consentOptin];
//Swift
DYApi.getInstance().consentOptin();
Indicates that a user does not want Dynamic Yield to collect and use their personal data.
- Opting out prevents future data collection from the current device/browser from all sections of the account, across all domains. This method overrides any past opt-in methods.
- If the visitor had opted out in the past, opting in will allow data collection moving forward.
For more details, see Visitor Data Privacy Management (GDPR Support).
Example
//Objective-C
[[DYApi getInstance] consentOptout];
//Swift
DYApi.getInstance().consentOptout();
Returns the views and purchases of one or more products over different time periods.Function Declaration
(BOOL)getProductActivityData:<wbr />(NSArray*)skus timeframe:(NSArray*)time includeProductInterest:(NSString*)interest includeProductData:(BOOL)>includeData andDelegate:(id<DYProductActivityDataDelegate>)delegate;
Parameters
- skus: Array of product SKUs
- time: An array of one or more values defining the timeframe going back. If undefined, returns values for all time periods. The values can be:
- TIME_FRAME_DAILY
- TIME_TWO_DAYS
- TIME_WEEKLY
- TIME_TWO_WEEKS
- TIME_MONTHLY
- interest: Determines if viewing data, purchase data, or both are returned. If undefined, both are returned. The values can be:
- PRODUCT_INTEREST_VIEW
- PRODUCT_INTEREST_PURCHASE
- includeData: Determines whether or not to display product attributes and details such as color, style, etc. The values can be YES or NO.
- delegate: A class instance that implements DYProductActivityDataDelegate Protocol
Example
[[DYApi getInstance] getProductActivityData:@[@"1",@"2"] timeframe:@[TIME_TWO_DAYS] includeProductInterest:PRODUCT_INTEREST_VIEW includeProductData:YES andDelegate:self];
Analytics
Reports an event to the Dynamic Yield server; returns Yes if props is not nil or empty.
-(BOOL)trackEvent:(NSString*)name prop:(NSDictionary*)props;
Parameters
- name: The unique name of the event as maintained in the Dynamic Yield Admin console
- props: Event properties dictionary, keys are as maintained in the Dynamic Yield Admin console
Example
//Objective-C
NSDictionary* purchaseProperties = [NSDictionary dictionaryWithObject:@"100" forKey:@"value"];
[_DY trackEvent:@"purchase" prop: purchaseProperties];
//Swift
var purchaseProperties = Dictionary<String, String>();
purchaseProperties["value"] = "100";
DYApi.getInstance().trackEvent("purchase", prop: purchaseProperties);
Requires SDK version 3.6.0
Reports an event to the Dynamic Yield server; returns Yes if props is not nil or empty.
-(BOOL)trackEvent:(NSString* _Nonnull)name prop:(NSDictionary* _Nullable)props completionHandler:(void (^_Nullable)(void))completionHandler;
Parameters
- name: The unique name of the event as maintained in the Dynamic Yield Admin console
- props: Event properties dictionary, keys are as maintained in the Dynamic Yield Admin console
- completionHandler: A runnable that is called when the event is received and ready to be used. This is used to wait for the event data to be available before running something that is dependent on that data (like a Dynamic Content campaign).
Example
//Objective-C
[[DYApi getInstance] trackEvent:@"button clicked" prop:@{@"name":@"purchase"} completionHandler:^(NSString * _Nonnull name) {
//run an experiment
}];
//Swift
var prop = Dictionary<String,String>();
prop["name"] = "purchase";
DYApi.getInstance().trackEvent(name, prop: prop ) { () in
//run an experiment
}
Reports an application page view to the Dynamic Yield server; returns Yes if the parameters are not nil or empty.
-(BOOL)pageView:(NSString*)uniqueId context:(DYPageContext*)DYContext;
Parameters
- uniqueId: Unique identifier of the page as maintained in the application
- context: (Optional) The current screen’s context, for details see Page Context for Mobile.
Example
//Objective-C
[_DY pageView:@"ABCD" context:context];
//Swift
DYApi.getInstance().pageView("pageUnique", context:context);
Requires SDK version 3.6.0
Reports an application page view to the Dynamic Yield server; returns Yes if the parameters are not nil or empty.
-(BOOL)pageView:(NSString* _Nonnull)uniqueID context:(DYPageContext* _Nullable)dyContext completionHandler:(void (^_Nullable)(void))completionHandler;
Parameters
- uniqueId: Unique identifier of the page as maintained in the application
- context: (Optional) The current screen’s context, for details see Page Context for Mobile.
- completionHandler: A runnable that is called when the pageview data is received by Dynamic Yield and ready to be used. This is used to wait for the pageview data to be available before running something that is dependent on that data (like a Dynamic Content campaign).
Example
//Objective-C
DYPageContext * homeContext = [
[DYPageContext alloc] init
];
[homeContext setType: DY_TYPE_HOMEPAGE];
[
[DYApi getInstance] pageView: @ "homepage"
context: homeContext completionHandler: ^ (NSString * _Nonnull name) {
//run an experiment
}
];
//Swift
let context = DYPageContext();
context.type = DY_TYPE_HOMEPAGE;
DYApi.getInstance().pageView("homepage", context: context) {
() in
//run an experiment
}
Sets the evaluator value, will remain valid until set again or until the session ends; returns Yes if input parameters are not nil or empty.
-(BOOL)setEvaluator:(NSString*)evaluatorID forParams:(NSArray*)params saveBetweenSessions:(BOOL)save;
Requires SDK version 2.6.3
Parameters
- key: The evaluator ID from DY’s admin console
- params: Array of the evaluator value(s)
- save: YES to save the evaluator value between sessions, NO to clear value when a new session starts
Example
//Objective-C
NSArray* values = [NSArray arrayWithObjects:@"winter",@"sale",@"women", nil];
[[DYApi getInstance] setEvaluator:EvalID forParams:values saveBetweenSessions:YES];
//Swift
let key = "199";
let values = ["winter","sale","women"];
DYApi.getInstance().setEvaluator(key, forParams: values, saveBetweenSessions:true);
Requires SDK version 3.6.0
Sets the evaluator value, will remain valid until set again or until the session ends; returns Yes if input parameters are not nil or empty.
-(BOOL)setEvaluator:(NSString* _Nonnull)evaluatorID forParams:(NSArray* _Nonnull)params saveBetweenSessions:(BOOL)save completionHandler:(void(^ _Nullable)(NSString* _Nonnull evaluatorID,NSArray* _Nonnull params,BOOL isPersistent))completionHandler;
Parameters
- key: The evaluator ID from DY’s admin console
- params: Array of the evaluator value(s)
- save: YES to save the evaluator value between sessions, NO to clear value when a new session starts
- completionHandler: A runnable that is called when the evaluator is set and ready to be used. This is used to wait for the evaluator to be set before running something that is dependent on the evaluator results (like a Dynamic Content campaign).
Example
//Objective-C
[
[DYApi getInstance] setEvaluator: @ "12345"
forParams: @[@ "red"] saveBetweenSessions: NO completionHandler: ^ (NSString * _Nonnull evaluatorID, NSArray * _Nonnull params, BOOL isPersistent) {
//run an experiment
}
];
//Swift
let prop = ["red"];
DYApi.getInstance().setEvaluator("123456", forParams: prop, saveBetweenSessions: false) { (name, params, isPersistent) in
//run an experiment
}
Messaging and Custom Actions
Requires SDK version 2.2
A delegate / listener method that allows you to control and manage content returned from a Messaging Overlay or Custom Action.
-(void)onSmartAction:(NSString* _Nonnull)smartActionID returned:(NSDictionary* _Nonnull)smartActionData onView:(UIView*)view;
This method is called after an Overlay or Custom Action has been triggered and a variation has been selected by Dynamic Yield. For Custom Actions the implementation of the method should include the desired app manipulation based on the JSON data returned. For Overlays where ‘shouldDYRender’ was set to ‘false’, this method allows manipulation and custom rendering based on the HTML data returned by Dynamic Yield.
Parameters
- smartActionID: The Smart Action ID as maintained in the Dynamic Yield Admin Console
- smartActionData: The variation data as maintained in the Dynamic Yield Admin Console; this can be either the Messaging Overlay HTML or the Custom Action JSON.
- view: The view of the overlay (if it exists)
Example
//Objective-C
NSDictionary * varData = [smartActionData objectForKey: @ "variationData"];
if ([smartActionID isEqualToString: @ "Reorder Homepage Menu"]) {
[globalProducts setHomepageOrder: varData];
}
//Swift
if (smartActionID == "Homepage reorder") {
let variation = smartActionData["variationData"];
setHomepageOrder(variation!);
}
For HTML Overlays, we provide a dedicated URI enabling closing the overlay: simply add “dycloseoverlay=true” as a URI parameter (e.g.:<your app>://<your deep link>?dycloseoverlay=true). Triggering this URI from within the Overlay’s HTML will close the overlay. This can be called using an href or using Javascript.
Variable Sets
Requires SDK version 1.8
Returns the value assigned to a variable name specified in parameter varName. The value is maintained in Dynamic Yield’s admin console. If there is no value assigned, the value specified in parameter defaultValue will be used. Notice the value will be returned with type id.
-(id)getSmartVariable:(NSString*)varName defaultValue:(id)defaultValue
Parameters
- varName: The name of the variable as maintained in the Dynamic Yield Admin Console
- defaultValue: The value that should be assigned to the variable in case no value is returned (e.g.the variable has been archived or deleted in the Dynamic Yield admin console). The value can be null, but make sure that this does not negatively impact your app.
Example
//Objective-C
[[DYApi getInstance] getSmartVariable:@"splashScreenText" defaultValue:@"Hello There!"];
//Swift
DYApi.getInstance().getSmartVariable("splashScreenText", defaultValue:" Hello There!");
Requires SDK version 3.7.0
Returns the value assigned to a variable name specified in parameter varName. The value is maintained in Dynamic Yield’s admin console. If there is no value assigned, the value specified in parameter defaultValue will be used. Notice the value will be returned with type id.
-(void)getSmartVariable:(NSString* _Nonnull)varName defaultValue:(id _Nullable)defaultValue completionHandler:(void(^_Nonnull)(id _Nonnull value))completionHandler;
Parameters
- varName: The name of the variable as maintained in the Dynamic Yield Admin Console
- defaultValue: The value that should be assigned to the variable in case no value is returned (e.g.the variable has been archived or deleted in the Dynamic Yield admin console). The value can be null, but make sure that this does not negatively impact your app.
Example
//Objective-C
[[DYApi getInstance] getSmartVariable:@"splashScreenText" completionHandler:^(id _Nonnull value) {
//do something with the result
}];
//Swift
DYApi.getInstance().getSmartVariable("splashScreenText") { (value) in
//do something with the result
};
Dynamic Content
Requires SDK version 1.9
Selects an HTML variation from the Dynamic Content defined in smartObjID and then assigns it to the WKWebView or UIWebView container defined in webView. Returns YES if the input parameters are valid. If parameter fallBackURL is maintained, the HTML content retrieved from the URL will be assigned to the webview container in case no variation is returned from the Dynamic Yield server and in case the control group variation was selected.
Use a delegate to respond to no returned results manually.
-(BOOL)loadWebView:(WKWebView* _Nullable)webView withSmartObject:(NSString* _Nonnull)smartObjID fallbackURL:(NSURL* _Nullable)fallBackURL;
Parameters
- webView: The WKWebView or UIWebView to which the Dynamic Content HTML content should be assigned
- smartObjID: The Dynamic Content ID or name as maintained in the Dynamic Yield admin console
- fallBackURL: A URL to the HTML content that should be loaded to the web view in case no Dynamic Content variation is returned from Dynamic Yield
Example
//Objective-C
NSString* url = @"https://www.example.com/Images/example.jpg";
WKWebView* homepageWebViewBanner = [[WKWebView alloc] initWithFrame:CGRectMake(0,0,width,height)];
[[DYApi getInstance] loadWebView:homepageWebViewBanner withSmartObject:@"Homepage Banner" fallbackURL:[NSURL URLWithString:url]];
//Swift
let web = WKWebView.init();
DYApi.getInstance().loadWebView(web, withSmartObject: "homepage banner", fallbackURL: nil);
Requires SDK version 3.6.0
Selects an HTML variation from the Dynamic Content defined in smartObjID and then assigns it to the WKWebView or UIWebView container defined in webView. Returns YES if the input parameters are valid. If parameter fallBackURL is maintained, the HTML content retrieved from the URL will be assigned to the webview container in case no variation is returned from the Dynamic Yield server and in case the control group variation was selected.
Use a delegate to respond to no returned results manually.
-(BOOL)loadWebView:(WKWebView* _Nullable)webView withSmartObject:(NSString* _Nonnull)smartObjID fallbackURL:(NSURL* _Nullable)fallBackURL completionHandler:(void (^_Nullable)(UIView* _Nullable webView,NSString* _Nonnull smartObjID,NSString* _Nullable data))completionHandler;
Parameters
- webView: The WKWebView or UIWebView to which the Dynamic Content HTML content should be assigned
- smartObjID: The Dynamic Content ID or name as maintained in the Dynamic Yield admin console
- fallBackURL: A URL to the HTML content that should be loaded to the web view in case no Dynamic Content variation is returned from Dynamic Yield
- completionHandler: A runnable that is called with the data from the Dynamic Content campaign (the same as the parameters for onSmartObjectLoadResult). This can be used instead of implementing the listener method onSmartObjectLoadResult.
Example
//Objective-C
[[DYApi getInstance] loadWebView:webView withSmartObject:@"homepage banner" fallbackURL:fallbackURL completionHandler:^(UIView * _Nullable webView, NSString * _Nonnull smartObjID, NSString * _Nullable data) {
//update the UI
}];
//Swift
DYApi.getInstance().load(webView, withSmartObject: "homepage banner" , fallbackURL: fallbackURL) { (view,smartObjID,data) in
//update the UI
}
Requires SDK version 2.6
Selects an image variation from the Dynamic Content defined in smartObjID and then assigns it to the UIImageView container defined in imageView. Returns YES if the input parameters are valid. Note that Dynamic Content variations with HTML content will not be rendered.
If parameter fallBackURL is maintained, the image retrieved from the URL will be assigned to the imageView container in case no variation is returned from the Dynamic Yield server and in case the control group variation was selected.
Use a delegate to respond to no returned results manually.
Note: Since this is an API for Dynamic Content with image content, use the Dynamic Yield template “Mobile Image” in all Dynamic Content variations.
Important: In order to avoid empty content, it is mandatory to either use Dynamic Content in a webView with existing content or to use a fallbackURL
-(BOOL)loadImageView:(UIImageView*)imageView withSmartObject:(id)smartObjID fallbackURL:(NSURL*)fallBackURL;
Parameters
- imageView: The image container to which the Dynamic Content image content should be loaded to
- smartObjID: The Dynamic Content ID or name as maintained in the Dynamic Yield admin console
- fallBackURL: A URL to an image that should be loaded to the image view in case no Dynamic Content variation is returned from Dynamic Yield
Example
//Objective-C
NSString* url = @"https://www.example.com/Images/example.jpg";
UIImageView* homepageImageViewBanner = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,width,height)];
[[DYApi getInstance] loadImageView:homepageImageViewBanner withSmartObject:@"Homepage Banner" fallbackURL:[NSURL URLWithString:url]];
//Swift
let image = UIImageView.init();
DYApi.getInstance().loadImageView(web, withSmartObject: "homepage banner", fallbackURL: nil);
Requires SDK version 3.6.0
Selects an image variation from the Dynamic Content defined in smartObjID and then assigns it to the UIImageView container defined in imageView. Returns YES if the input parameters are valid. Note that Dynamic Content variations with HTML content will not be rendered.
If parameter fallBackURL is maintained, the image retrieved from the URL will be assigned to the imageView container in case no variation is returned from the Dynamic Yield server and in case the control group variation was selected.
Use a delegate to respond to no returned results manually.
Note: Since this is an API for Dynamic Content with image content, use the Dynamic Yield template “Mobile Image” in all Dynamic Content variations.
Important: In order to avoid empty content, it is mandatory to either use Dynamic Content in a webView with existing content or to use a fallbackURL
-(BOOL)loadImageView:(UIImageView* _Nullable)imageView withSmartObject:(id _Nonnull)smartObjID fallbackURL:(NSURL* _Nullable)fallBackURL completionHandler:(void (^_Nullable)(UIView* _Nullable webView,NSString* _Nonnull smartObjID,NSString* _Nullable data))completionHandler;
Parameters
- imageView: The image container to which the Dynamic Content image content should be loaded to
- smartObjID: The Dynamic Content ID or name as maintained in the Dynamic Yield admin console
- fallBackURL: A URL to an image that should be loaded to the image view in case no Dynamic Content variation is returned from Dynamic Yield
- completionHandler: A runnable that is called with the data from the Dynamic Content campaign (the same as the parameters for onSmartObjectLoadResult). This can be used instead of implementing the listener method onSmartObjectLoadResult.
Example
//Objective-C
[[DYApi getInstance] loadImageView:imageView withSmartObject:@"homepage banner" fallbackURL:fallbackURL completionHandler:^(UIView * _Nullable webView, NSString * _Nonnull smartObjID, NSString * _Nullable data) {
//update the UI
}];
//Swift
DYApi.getInstance().load(imageView, withSmartObject: "homepage banner", fallbackURL: fallbackURL) { (view,smartObjID,data) in
//update the UI
}
A delegate method called with the return of a Dynamic Content variation. Enables responding to the returned content before rendering (e.g. do not render the webview if the result is empty for any reason).
-(void)smartObject:(NSString*)smartObjID returned:(NSString*)html on:(UIWebView*)webView;
Parameters
- smartObjID: The Dynamic Content ID or name as maintained in the Dynamic Yield admin console
- webView: The UIWebView to which the Dynamic Content HTML content is assigned
- html: The Dynamic Content variation HTML content returned by Dynamic Yield
Example
//Objective-C
-(void) smartObject: (NSString * ) smartObjID returned: (NSString * ) html on: (UIWebView * ) webView {
if (!html) {
webView.hidden = YES;
}
}
//Swift
func smartObject(smartObjID: String!, returned html: String!, on webView: UIWebView!) {
if (html == nil) {
webView.hidden = true;
}
}
Chooses a Dynamic Content variation, returns the content as a JSON object, and reports an impression. If a user views the same variation more than once without calling the API again, call trackSmartObjectImpressions to report additional impressions. Call trackSmartObjectClickedevery time a user clicks on a Dynamic Content variation created using the getSmartObjectData API to report a click.
-(NSDictionary*)getSmartObjectData:(id)smartObjectID
Parameter
- smartObjectID: The ID of the Dynamic Content campaign
Example Call
//Objective-C
[[DYApi getInstance] getSmartObjectData:@"Your_Dynamic_Content_Campaign_ID"];
//Swift
DYApi.getInstance().getSmartObjectData("Your_Dynamic_Content_Campaign_ID");
Return Value
A JSON object that contains the following items:
- params : The JSON object with all variables and values (the content from the Variables tab in the user interface when creating variations)
- selectedVar – The content of the HTML, CSS, and JS tabs from the user interface combined into one string
Example Return (Updated in SDK 3.4.0)
{
"params": {
"html": {
"htmlVarA": "valueA",
"htmlVarB": "valueB"
},
"css": {
"cssVarA": "valueA",
"cssVarB": "valueB"
},
"js": {
"jsVarA": "valueA",
"jsVarB": "valueB"
},
"rcom": {
"rcomVarA": "valueA",
"rcomVarB": "valueB"
}
},
"selectedVar": ""
}
Chooses a Dynamic Content variation, returns the content as a JSON object, and reports an impression. If a user views the same variation more than once without calling the API again, call trackSmartObjectImpressions to report additional impressions. Call trackSmartObjectClickedevery time a user clicks on a Dynamic Content variation created using the getSmartObjectData API to report a click.
-(void)getSmartObjectData:(id _Nonnull )smartObjectID completionHandler:(void(^_Nonnull)(NSDictionary* _Nonnull data))completionHandler;
Parameter
- smartObjectID: The ID of the Dynamic Content campaign
- completionHandler: A callback function with the data
Example Call
//Objective-C
[[DYApi getInstance] getSmartObjectData:@"Your_Dynamic_Content_Campaign_ID" completionHandler:^(NSDictionary * _Nonnull data) {
//do something with the result
}];
//Swift
DYApi.getInstance().getSmartObjectData("Your_Dynamic_Content_Campaign_ID") { (data) in
//do something with the result
};
Return Value
A JSON object that contains the following items:
- params : The JSON object with all variables and values (the content from the Variables tab in the user interface when creating variations)
- selectedVar – The content of the HTML, CSS, and JS tabs from the user interface combined into one string
Example Return (Updated in SDK 3.4.0)
{
"params": {
"html": {
"htmlVarA": "valueA",
"htmlVarB": "valueB"
},
"css": {
"cssVarA": "valueA",
"cssVarB": "valueB"
},
"js": {
"jsVarA": "valueA",
"jsVarB": "valueB"
},
"rcom": {
"rcomVarA": "valueA",
"rcomVarB": "valueB"
}
},
"selectedVar": ""
}
Reports to Dynamic Yield that a user viewed a Dynamic Content variation created by using the getSmartObjectData API. An impression is already counted every time a getSmartObjectData call is made, but if a user views the same variation more than once without calling getSmartObjectDataagain, call this API to report additional impressions.
(void)trackSmartObjectImpression:(NSString*)smartName;
Parameter
- smartName: The ID of the Dynamic Content campaign
Example Call
//Objective-C
[[DYApi getInstance] trackSmartObjectImpression:@"Your_Dynamic_Content_Campaign_ID"];
//Swift
DYApi.getInstance().trackSmartObjectImpression("Your_Dynamic_Content_Campaign_ID");
Reports to Dynamic Yield that a user clicked on a Dynamic Content variation created by using the getSmartObjectData API.
-(void)trackSmartObjectClicked:(NSString*)smartName;
Parameter
- smartName: The ID of the Dynamic Content campaign
Example Call
/Objective-C
[[DYApi getInstance] trackSmartObjectClicked:@"Your_Dynamic_Content_Campaign_ID"];
//Swift
DYApi.getInstance().trackSmartObjectClicked("Your_Dynamic_Content_Campaign_ID");
Push Notification
Requires SDK version 3.0
Request permission to receive push notifications from the app.
- (void)registerForPushNotifications;
Example
//Objective-C
[[DYApi getInstance] registerForPushNotifications];
//Swift
DYApi.getInstance().registerForPushNotifications();
Pass the user’s device push token (PushID) to Dynamic Yield.
-(BOOL)setPushNotificationID:(NSData*)pushID;
Parameter
- pushID: The user’s push token.
Example
//Objective-C
[[DYApi getInstance] setPushNotificationID:deviceToken];
//Swift
DYApi.getInstance().setPushNotificationID(deviceToken);
Opts the user into receiving Dynamic Yield’s triggered push notification.
-(BOOL)subscribeToPushNotifications;
Example
//Objective-C
[[DYApi getInstance] subscribeToPushNotifications];
//Swift
DYApi.getInstance().subscribeToPushNotifications();
Request permission to receive push notifications from the app.
-(BOOL)unsubscribeFromPushNotifications;
Example
//Objective-C
[[DYApi getInstance] unsubscribeFromPushNotifications];
//Swift
DYApi.getInstance().unsubscribeFromPushNotifications();
Product Recommendations
Requires SDK version 2.0
Get the recommended items for a given widget id in a specified context. The results are returned via the delegate.
-(BOOL)sendRecommendationRequest:(NSString*)widgetID withContext:(DYPageContext*)context itemsIDsOnly:(BOOL)itemsIDsOnly andDelegate:(id)rcomDelegate;
-(BOOL)sendRecommendationRequest:(NSString*)widgetID withContext:(DYPageContext*)context itemsIDsOnly:(BOOL)itemsIDsOnly pageNumber:(int)pageNumber pageSize:(int)pageSize andDelegate:(id)rcomDelegate;
Parameters
- widgetID: The recommendation widget ID as maintained in the Dynamic Yield admin console
- context: The current screen’s context, see details in Dynamic Yield Context Object
- itemIDsOnly: Used to request only the recommended item’s identifiers (without additional item metadata).
- rcomDelegate: A delegate that receives the results and handles the recommended items presentation, see onRecommendationResults
Pagination Parameters (beta)
The pagination parameters let you break down recommendation results into multiple pages and control how many items are on each page. They can only be used for recommendations that meet following conditions:
- Page type is homepage, category, or other
- Algorithm is popularity or user affinity, and the same algorithm must be used for all slot
- There are no dynamic filters (no excludes, no shuffle, etc.)
- If any filtering rules are used, they must be of type “exclude” or “only include”, and must be applied to all slots.
We recommend contacting your Customer Success Manager before using these parameters to make sure they are implemented properly.
The pagination parameters are:
- pageSize: determines the number of recommended items in each page
- pageNumber: determines the page number when recommendations results are broken down to multiple pages
Example
//Objective-C
DYPageContext* context = [[DYPageContext alloc] init];
[context setLanguage:@"en_GB"];
[context setType:DY_TYPE_PRODUCT];
[context setData:@[@"101"]];[[DYApi getInstance] sendRecommendationRequest:widgetID withContext:context itemsIDsOnly:YES andDelegate:self];
//Swift
let context = DYPageContext.init();
context.data = [];
context.language = "us_GB";
context.type = DY_TYPE_HOMEPAGE;DYApi.getInstance().sendRecommendationRequest("991", withContext: context, itemsIDsOnly: true, andDelegate: self);
Get the recommended items for a given widget id in a specified context. The results are returned via the delegate.
-(BOOL)sendRecommendationRequest:(NSString* _Nonnull)widgetID withContext:(DYPageContext* _Nonnull)context completionHandler:(void (^_Nullable)(NSArray* _Nullable recommendations,NSString* _Nonnull widgetID))completionHandler;
-(BOOL)sendRecommendationRequest:(NSString* _Nonnull)widgetID withContext:(DYPageContext* _Nonnull)context pageNumber:(int)pageNumber pageSize:(int)pageSize
completionHandler:(void (^_Nullable)(NSArray* _Nullable recommendations,NSString* _Nonnull widgetID))completionHandler;
Parameters
- widgetID: The recommendation widget ID as maintained in the Dynamic Yield admin console
- context: The current screen’s context, see details in Dynamic Yield Context Object
- itemIDsOnly: Used to request only the recommended item’s identifiers (without additional item metadata).
- completionHandler: A runnable that is called with the recommendation results. This is used to wait for the recommendation data.
Pagination Parameters (beta)
The pagination parameters let you break down recommendation results into multiple pages and control how many items are on each page. They can only be used for recommendations that meet following conditions:
- Page type is homepage, category, or other
- Algorithm is popularity or user affinity, and the same algorithm must be used for all slot
- There are no dynamic filters (no excludes, no shuffle, etc.)
- If any filtering rules are used, they must be of type “exclude” or “only include”, and must be applied to all slots.
We recommend contacting your Customer Success Manager before using these parameters to make sure they are implemented properly.
The pagination parameters are:
- pageSize: determines the number of recommended items in each page
- pageNumber: determines the page number when recommendations results are broken down to multiple pages
Example
//Objective-C
DYPageContext* homeContext = [[DYPageContext alloc] init];
[homeContext setType:DY_TYPE_HOMEPAGE];
[[DYApi getInstance] sendRecommendationRequest:@"123456" withContext:homeContext completionHandler:^(NSArray * _Nullable recommendations, NSString * _Nonnull widgetID) {
//render the recommendations
}];
//Swift
let context = DYPageContext();
context.type = DY_TYPE_HOMEPAGE;
DYApi.getInstance().sendRecommendationRequest("123456", with: context, completionHandler: {
(items, widgetID) in
//render recommendations
});
Get the recommended items for a given widget id in a specified context. The results are returned via the completion handler according to the filter.
-(BOOL)sendRecommendationRequest:(NSString* _Nonnull)widgetID
withContext:(DYPageContext* _Nonnull)context andFilters:(NSArray<DYRCOMFilter*>*_Nonnull)filter
completionHandler:(void (^_Nullable)(NSArray* _Nullable recommendations,NSString* _Nonnull widgetID))completionHandler;
Parameters
- widgetID: The recommendation widget ID as maintained in the Dynamic Yield admin console
- context: The current screen’s context. For details, see DY Page Context in Additional Classes below
- filter: A filter that limits the results defined using the DYRCOMFilter class. For details, see Additional Classes below.
- completionHandler: A runnable that is called with the recommendation results. This is used to wait for the recommendation data.
Example
//Objective-C
DYPageContext* homeContext = [[DYPageContext alloc] init];
[homeContext setType:DY_TYPE_HOMEPAGE];
[[DYApi getInstance] sendRecommendationRequest:@"123456"
withContext:homeContext
andFilters:@[[DYRCOMFilter filterWithType:DY_FILTER_EXCLUDE Field:DY_FILTER_GROUP_ID Value:@[@"ZMB1598W725"]],
[DYRCOMFilter filterWithType:DY_FILTER_INCLUDE Field:DY_FILTER_SKU Value:@[@"WT0!"]]]
completionHandler:^(NSArray * _Nullable recommendations, NSString * _Nonnull widgetID) {
//render the recommendations
}];
//Swift
let context = DYPageContext();
context.type = DY_TYPE_HOMEPAGE;
DYApi.getInstance().sendRecommendationRequest("123456",
with: context,
andFilters:[DYRCOMFilter (type: DY_FILTER_INCLUDE, field: DY_FILTER_SKU, value: ["WT01"]),
DYRCOMFilter (type: DY_FILTER_EXCLUDE, field: DY_FILTER_GROUP_ID, value: ["75937"])],
completionHandler: { (items, widgetID) in
//render recommendations
});
Get the recommended items for a given widget id in a specified context, only return products that adhere to a set of filters set in real-time. The results are returned via the delegate.
-(BOOL)sendRecommendationRequest:(NSString* _Nonnull)widgetID withContext:(DYPageContext* _Nonnull)context realtimeRules:(NSArray*_Nonnull)realtimeRules completionHandler:(void (^_Nullable)(NSArray* _Nullable recommendations,NSString* _Nonnull widgetID))completionHandler;
Parameters
- widgetID: The recommendation widget ID as maintained in the Dynamic Yield admin console
- context: The current screen’s context. For details, see DY Page Context in Additional Classes below
- realtimeRules: Array of NSDictionary objects that filters the results.
- completionHandler: A runnable that is called with the recommendation results. This is used to wait for the recommendation data.
Example
//Objective-C
NSString* realtimeRules = @"[{\"priority\":0,\"id\":-1,\"isContextAware\":false,\"query\":{\"conditions\":[{\"field\":\"sku\",\"arguments\":[{\"action\":\"IS\",\"value\":\"1002003-400\"}]}]},\"type\":\"include\",\"slots\":[0]}]";
NSData* data = [realtimeRules dataUsingEncoding:NSUTF8StringEncoding];
NSArray *realtimeRulesObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
[[DYApi getInstance] sendRecommendationRequest:@"31002" withContext:[self getHomeContext] realtimeRules:realtimeRulesObject completionHandler:^(NSArray * _Nullable recommendations, NSString * _Nonnull widgetID) {
//do something with the results
}];
//Swift
do {
let context = DYPageContext();
context.type = DY_TYPE_HOMEPAGE;
let jsonString = "[{\"priority\":0,\"id\":-1,\"isContextAware\":false,\"query\":{\"conditions\":[{\"field\":\"sku\",\"arguments\":[{\"action\":\"IS\",\"value\":\"1002003-400\"}]}]},\"type\":\"include\",\"slots\":[0]}]";
let data = jsonString.data(using: .utf8)!
let jsonArray = try (JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>])!
DYApi.getInstance().sendRecommendationRequest("44435", with: context, realtimeRules: jsonArray, completionHandler: { (items, widgetID) in
//do something with the results
})
} catch let error as NSError {
print(error)
}
A listener method called with the return of the recommendation results. This is where the rendering logic of the returned recommended items should take place. The response is an array of JSON objects, each item in the returned array includes the available metadata for every recommendation item.
-(void)onRecommendationResult:(NSArray* _Nullable)recommendations forWidgetID:(NSString* _Nonnull)widgetID;
Parameters
- recommendation: An array of the recommended items returned by the sendRecommendationRequest call
- widgetID
Response Example
// itemIDsOnly = false (full item metadata) - each JSON object includes:
{
"item": {
"sku": "101",
"description": "JJ Supreme Basketball Shoes",
"url": "https://www.example.com/item/101",
"gender": "WOMENS",
"price": 100,
"image_url": " https://www.example.com/images/101.jpg",
"dy_item_type": "product",
"name": "JJ Basketball shoes"
},
"strId": 1,
"md": {}
}
}
//itemIDsOnly = true - each JSON object includes:
{
"item": {
"sku": "101"
},
"strId": 1,
"md": {}
}
}
Example
//Objective-C
-(void)onRecommendationResult:(NSArray *)recommendations forWidgetID:(NSString* _Nonnull)widgetID{
// rendering the recommended items
}
//Swift
func onRecommendationResult(recommendations: [AnyObject]!, forWidgetID widgetID: String) {
// rendering the recommended items
Sets the current user’s affinity as response to explicit indication by the user. Returns YES if the input parameters are valid.
-(BOOL)setRecommendationAffinities:(NSDictionary*)affinities;
Parameter
- affinities: Key value pairs where the keys are product attributes and the value is an array of the attribute values
Example
//Objective-C
NSDictionary *affinities = [NSDictionary dictionaryWithObjectsAndKeys:
@[@"loose"], @"style", @[@"red"], @"color",nil];
[[DYApi getInstance] setRecommendationAffinities:affinities];
//Swift
var aff = = Dictionary<String, Array>();
aff["color"] = ["red"];
aff["style"] = ["loose"];
DYApi.getInstance().setRecommendationAffinities(aff);
Reports a list of recommended items real impressions (i.e. were visible to user) within a given recommendation widget to the Dynamic Yield server. Returns YES if the input parameters are valid.
-(BOOL)TrackRecomItemsRealImpression:(NSString*)widgetID andItemID:(NSArray*)itemIDs;
Parameters
- widgetID: The recommendation widget ID used for receiving the recommendations items presented to the user
- itemIDs: An array of identifiers of recommendation items presented to the user
Example
//Objective-C
[[DYApi getInstance] TrackRecomItemsRealImpression:@”991” andItemIDs:@[@”101”, @”102”, @”103”, nil]];
//Swift
DYApi.getInstance().TrackRecomItemsRealImpression("991", andItemIDs: ["101", “102”, “103”]);
Reports the identifier of a recommended item tapped by the user within a given recommendation widget to the Dynamic Yield server. Returns YES if the input parameters are valid.
-(BOOL)TrackRecomItemClick:(NSString*)widgetID andItemID:(NSString*)itemID;
Parameters
- widgetID: The recommendation widget ID used for receiving the recommendations items presented to the user
- itemID: The identifier of a recommendation items tapped by the user
Example
//Objective-C
[[DYApi getInstance] TrackRecomItemClick:@”991” andItemID:@”101”];
//Swift
DYApi.getInstance().TrackRecomItemClick("991", andItemID: "101");
Additional Classes
A helper class storing the screen’s context attributes (e.g. required for recommendations). For more details, see Page Context for Mobile.
init
Returns an allocated DYPageContext instance
+ (DYPageContext*)init;
Set and Get
You can set and get the following properties which are part of the DYPageContext object
@property (strong, atomic) NSString* language;
The user’s locale in format:
_
For example, en_US or fr_CA
@property (strong, atomic) NSString* type;
The screen type from the following enum: DY_TYPE_HOMEPAGE, DY_TYPE_PRODUCT, DY_TYPE_CATEGORY, DY_TYPE_CART, DY_TYPE_POST
@property (strong, atomic) NSArray[]* data;
The specific data for the current page context
- For DY_TYPE_HOMEPAGE: no context data
- For DY_TYPE_CATEGORY: an array of all of the page’s categories, e.g. [“Mens”, “Tops”, …]
- For DY_TYPE_PRODUCT: The SKU of the product displayed in the page, e.g. [“sku435-1a”]
- For DY_TYPE_CART: an array of all the SKUs in the cart, e.g. [“sku435-1a”, “sku98123”]
- For DY_TYPE_POST: The Post ID of the post displayed in the page, e.g. [“vid-3321-lng”]
- For DY_TYPE_OTHER: no context data
Example
//Objective-C
DYPageContext* context = [[DYPageContext alloc] init];
[context setLanguage:@"en_GB"];
[context setType:DY_TYPE_PRODUCT];
[context setData:@[@"101"]];
//Swift
let context = DYPageContext.init();
context.data = ["101"];
context.language = "en_GB";
context.type = DY_TYPE_PRODUCT;
A helper class storing user profile attributes.
create
Returns an allocated DYUserData instance
+ (DYUserData*)create;
Set and Get
You can set and get the following properties which are part of the DYUserData object
@property (strong, atomic) NSString* email; //SHA 256 hashed email of the plain text email in lower case
@property (strong, atomic) NSString* externalUserID; //The user’s unique identifier as maintained in your system
Example
//Objective-C
DYUserData* user = [DYUserData create];
//SHA 256 hashed email of the plain text email in lower case
[user setEmail:@"18B258E9ADE091623DD829132E1E9D8B4A7F7D90ABEA194001C54341C3F27B79"];
//Swift
let user = DYUserData.create();
user.email = "18B258E9ADE091623DD829132E1E9D8B4A7F7D90ABEA194001C54341C3F27B79";
A helper class that filters the results of a recommendation request call, including and excluding products by their SKU or groupID
filterWithType:Field:Value:
+(DYRCOMFilter*)filterWithType:(DYFilterType)filterType
Field:(DYFilterField)filterField Value:(NSArray*)value;
Parameters
- filterType: Must be either DY_FILTER_INCLUDE or DY_FILTER_EXCLUDE
- filterField: Must be either DY_FILTER_SKU or DY_FILTER_GROUP_ID
- value: An array of SKUs or groupIDs that define what is excluded or included.
Return Value
A DYRCOMFilter object
Example
//objective C
[DYRCOMFilter filterWithType:DY_FILTER_INCLUDE Field:DY_FILTER_SKU Value:@[@"WT0!"]
//swift
DYRCOMFilter (type: DY_FILTER_EXCLUDE, field: DY_FILTER_GROUP_ID, value: ["75937"])
Removed Items
The items in this section have been completely removed from our code.
Chooses a variation for a given experiment and returns information about the variation, including the experiment variation name, id, and a JSON object containing all additional properties set in the Dynamic Yield admin console.
-(NSDictionary*)forceChooseVariationAndGetData:(id)expID;
Parameter
- expId: The experiment name or id
Example
//Objective-C
NSDictionary props = [_DY chooseVariationAndGetData:@"login experiment"];
//Swift
var props = Dictionary<String, String>();
props = DYApi.getInstance().chooseVariationAndGetData("login experiment");
Chooses a variation for the given experiment ID or name and returns the variation data in a dictionary object from the Dynamic Yield server, regardless of previous results (for example, when a variation is configured to be chosen once per session).
-(NSDictionary*)forceChooseVariationAndGetData:(id)expID;
Parameter
- expId: The experiment name or id
Example
//Objective-C
NSDictionary props = [_DY forceChooseVariationAndGetData:@"login experiment"];
//Swift
var props = Dictionary<String, String>();
props = DYApi.getInstance().forceChooseVariationAndGetData("login experiment");
Reports an article tapped within the Front Page view by the user to the Dynamic Yield server; returns Yes if articleID or frontpageID is not nil or empty.
-(BOOL)trackFrontpage:(NSString*)frontpageID articleClicked:(NSString*)articleID inSection:(NSString*)section position:(int)position;
Parameters
- frontpageID: The frontpage ID as maintained in the Dynamic Yield Admin Console
- articleID: The article ID as maintained in the Dynamic Yield Admin Console (in the frontpage data feed)
- section: The section / unit ID as maintained in the Dynamic Yield Admin Console (in the frontpage data feed)
- position: The position of the tapped article within the unit as maintained in the Dynamic Yield Admin Console (in the frontpage data feed)
Example
//Objective-C
[_DY trackFrontpage:@”mainHomePage” articleClicked: @”www.examplenews.com/article1234.html” inSection:@”Sports” positon:2];
Returns information about the chosen variations of the specified article experiment running in the specified Front Page from the Dynamic Yield server. Returned data includes the article ID, the chosen variation id, article title, article image and article catchline.
-(NSDictionary*) getExperimentDataFor:(NSString*)articleID inFrontpage:(NSString*)frontpageID andSection:(NSString*)section;
Parameters
- articleID: The article ID as maintained in the Dynamic Yield Admin Console (in the frontpage data feed)
- frontpageID: The frontpage ID as maintained in the Dynamic Yield Admin Console
- section: The section / unit ID as maintained in the Dynamic Yield Admin Console (in the frontpage data feed)
Example
//Objective-C
NSDictionary* articleExperimentData = [_DY getExperimentDataFor: @”www.examplenews.com/article1234.html” inFrontpage:@”mainHomePage” andSection:”sports”];
Returns information about the chosen variations of the specified article experiment running in the specified Front Page from the Dynamic Yield server. Returned data includes the article ID, the chosen variation id, article title, article image and article catchline.
- (NSDictionary*)getAllExperimentsDataForFrontpage:(NSString*)frontpageID;
Parameter
- frontpageID: The frontpage ID as maintained in the Dynamic Yield Admin Console
Example
//Objective-C
NSDictionary* allArticleExperimentData = [_DY getAllExperimentsDataForFrontpage:@”mainHomePage”];
Reports an application page view to the Dynamic Yield server; returns Yes if the parameters are not nil or empty.
- (BOOL)pageView:(NSString*)uniqueId name:(NSString*)name section:(NSString*)section context:(DYPageContext*)context;
Parameters
- uniqueId: Unique identifier of the page as maintained in the application
- name: Display name of the page, will be used in the Dynamic Yield analytics reports
- section: (Optional) The section that hold the page – can be nil
- context: (Optional) The current screen’s context, for details see Page Context for Mobile.
Example
//Objective-C
[_DY pageView:@"ABCD" name:[self getPageName] section:@”news” context:context];
//Swift
DYApi.getInstance().pageView("pageUnique",name:"pageName", section:"sports" context:context);
Enables Dynamic Yield to automatically track page views whenever a new page is loaded. By default this is not enabled, meaning page views are tracked via an explicit API call.
-(void)setAutoPageViewsTracking:(BOOL)enabled
Parameter
- enabled: True will enable the implicit pave view tracking
Example
//Objective-C
[[DYApi getInstance] setAutoPageViewsTracking:true];
//Swift
DYApi.getInstance().setAutoPageViewsTracking(true);
Reports a list of unit impressions to the Dynamic Yield server; returns Yes if names is not nil or empty.
-(BOOL)trackUnitsImpression:(NSArray*)names;
Parameter
- names: Array of unit names as maintained in the Dynamic Yield Admin Console
Example
//Objective-C
NSArray* units = [NSArray arrayWithObjects:@"sports",@"news",@"celebs", nil];
[_DY trackUnitsImpression:units];
//Swift
DYApi.getInstance().trackUnitsImpression(["sports", “news”]);
Reports a list of unit real impressions (i.e. were visible to user) to the Dynamic Yield server; returns Yes if names is not nil or empty.
- (BOOL)trackUnitsRealImpression:(NSArray*)names;
Parameter
- names: Array of unit names as maintained in the Dynamic Yield Admin Console
Example
//Objective-C
NSArray* units = [NSArray arrayWithObjects:@"sports",@"news",@"celebs", nil];
[_DY trackUnitsRealImpression:units];
//Swift
DYApi.getInstance().trackUnitsRealImpression(["sports", “news”]);
Reports a list of unit tapped by the user to the Dynamic Yield server; returns Yes if names is not nil or empty.
- (BOOL)trackUnitsClicked:(NSArray*)name;
Parameter
- names: Array of unit names as maintained in the Dynamic Yield Admin Console
Example
//Objective-C
[_DY trackUnitsClicked:@"sports"];
//Swift
DYApi.getInstance().trackUnitsClicked("sports");
Sets the site variables sent with each event, these variables are sticky until clear method is triggered; returns Yes if vars is not nil or empty.
- (BOOL)setSiteVars:(NSDictionary*)vars;
Parameter
- vars: Dictionary of the site variables; only keys defined in the Dynamic Yield Admin Console are persisted
Example
//Objective-C
NSDictionary* siteVars = [NSMutableDictionary dictionary];
[siteVars setValue:[self getCurrentDay] forKey:DAY_KEY];
[_DY setSiteVars:siteVars];
//Swift
var siteVars = Dictionary<String, String>();
siteVars["appVersion"] = "1.22";
DYApi.getInstance().setSiteVars(siteVars);
Clears the value of the site variables sent within the array names; returns Yes if names is not nil or empty.
- (BOOL)clearSiteVars:(NSArray*)names;
Parameter
- names: Array of site variable names as maintained in the Dynamic Yield Admin Console
Example
//Objective-C
NSArray* clear = [NSArray arrayWithObject:DAY_KEY];
[_DY clearSiteVars:clear];
//Swift
DYApi.getInstance().clearSiteVars([“siteVarName”]);
This method is called when DY scripts are ready.
OnInitReply
Called after the server responded the initialization request
-(void)onInitReply:(InitReply)initStatus
Parameter
- initStatus: An enum holding the init state with the following possible values:
- DY_NOT_INITIALIZED no server call has been made
- DY_INIT_CALLED a server call was sent
- DY_SECTION_INACTIVE the section is inactive or the secret key is incorrect
- DY_INIT_FAILED the server can’t respond or an error has occurred
- DY_INIT_OK the server call was successful
Example
//obj-c
-(void) onInitReply: (InitReply) initStatus {
BOOL res = (initStatus == DY_INIT_OK);
if (res) {
//..do something
}
}
//swift
func onInitReply(initStatus: InitReply) {
if (initStatus == DY_INIT_OK) {
//..do something
}
}
Sets the evaluator value, will remain valid until set again or until the session ends; returns Yes if input parameters are not nil or empty.
-(BOOL)setEvaluator:(NSString*) key forParams(NSArray*)params;
Parameters
- key: The evaluator ID from DY’s admin console
- params: Array of the evaluator value(s)
Example
//Objective-C
NSArray* values = [NSArray arrayWithObjects:@"winter",@"sale",@"women", nil];
[[DYApi getInstance] setEvaluator:EvalID forParams:values];
//Swift
let key = "199";
let values = ["winter","sale","women"];
DYApi.getInstance().setEvaluator(key, forParams: values);
This method is called just before the HTML Overlay content is rendered by Dynamic Yield and allows preventing its rendering. The default value is ‘true’.
-(BOOL)shouldDYRender:(NSString*)smartActionID;
Parameter
- smartActionID: The Smart Action ID as maintained in the Dynamic Yield Admin Console
Example
//Objective-C
if ([smartActionID isEqualToString: @ "Homepage"]) {
return false;
}
return true;
//Swift
if (smartActionID == "Homepage order") {
return false;
}
return true;
A listener method called with the return of the recommendation results. This is where the rendering logic of the returned recommended items should take place. The response is an array of JSON objects, each item in the returned array includes the available metadata for every recommendation item.
-(void)onRecommendationResult:(NSArray *)recommendations;
Parameter
- recommendation: An array of the recommended items returned by the sendRecommendationRequest call
Response Example
// itemIDsOnly = false (full item metadata) - each JSON object includes:
{
"item": {
"sku": "101",
"description": "JJ Supreme Basketball Shoes",
"url": "https://www.example.com/item/101",
"gender": "WOMENS",
"price": 100,
"image_url": " https://www.example.com/images/101.jpg",
"dy_item_type": "product",
"name": "JJ Basketball shoes"
},
"strId": 1,
"md": {}
}
}
//itemIDsOnly = true - each JSON object includes:
{
"item": {
"sku": "101"
},
"strId": 1,
"md": {}
}
}
Example
//Objective-C
-(void)onRecommendationResult:(NSArray *)recommendations{
// rendering the recommended items
}
//Swift
func onRecommendationResult(recommendations: [AnyObject]!) {
// rendering the recommended items
iOS is a trademark of Apple Inc., registered in the U.S. and other countries and regions.