Event Code Samples
iOS Event Code Samples
the following events are available to use in the ios version of the monetate sdk metadata event metadata event code example import uikit import monetate ios sdk @main class appdelegate uiresponder, uiapplicationdelegate { let requestid = "123456" var window uiwindow? final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) func application( application uiapplication, didfinishlaunchingwithoptions launchoptions \[uiapplication launchoptionskey any]? ) > bool { metadataapi() return true } func metadataapi() { let languagedata = jsonvalue(dictionaryliteral ("language", "en us")) let jsonval = jsonvalue(dictionaryliteral ("metadata", languagedata)) objpersonalization report(context metadata, event metadata(metadata jsonval)) } } screen size event screensize event code example import uikit import monetate ios sdk @main class appdelegate uiresponder, uiapplicationdelegate { let requestid = "123456" var window uiwindow? final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) func application( application uiapplication, didfinishlaunchingwithoptions launchoptions \[uiapplication launchoptionskey any]? ) > bool { screensizeapi() return true } func screensizeapi() { let (width, height) = miscclass getdevicesize() objpersonalization report( context screensize, event screensize(height int(truncating width), width int(truncating height))) } } user agent event useragent event code example import uikit import monetate ios sdk @main class appdelegate uiresponder, uiapplicationdelegate { let requestid = "123456" var window uiwindow? final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) func application( application uiapplication, didfinishlaunchingwithoptions launchoptions \[uiapplication launchoptionskey any]? ) > bool { useragentapi() return true } func useragentapi() { let useragent = wkwebview() value(forkey "useragent") as! string objpersonalization report(context useragent, event useragent(useragent useragent)) } } coordinates event reports the coordinates of the customer coordinates event code example import uikit import monetate ios sdk @main class appdelegate uiresponder, uiapplicationdelegate { let requestid = "123456" var window uiwindow? final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) func application( application uiapplication, didfinishlaunchingwithoptions launchoptions \[uiapplication launchoptionskey any]? ) > bool { coordinateapi() return true } func coordinateapi() { let coordinates = coordinates(latitude "11 2734", longitude "45 2734") objpersonalization report(context coordinates, event coordinates) } } referrer event reports the referrer referrer event code example import uikit import monetate ios sdk @main class appdelegate uiresponder, uiapplicationdelegate { let requestid = "123456" var window uiwindow? final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) func application( application uiapplication, didfinishlaunchingwithoptions launchoptions \[uiapplication launchoptionskey any]? ) > bool { referrerapi() return true } func referrerapi() { let referrer = referrer(referrer "www monetate com") objpersonalization report(context referrer, event referrer) } } custom variable event reports custom variables customvariable event code example import uikit import monetate ios sdk @main class appdelegate uiresponder, uiapplicationdelegate { let requestid = "123456" var window uiwindow? final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) func application( application uiapplication, didfinishlaunchingwithoptions launchoptions \[uiapplication launchoptionskey any]? ) > bool { customvariableapi() return true } func customvariableapi() { let customvariable = customvariables(customvariables \[ customvariablesmodel(variable "favoriteteam", value "blue hens") ]) objpersonalization report(context customvariables, event customvariable) } } page event reports any events on the page pageevent code example import uikit import monetate ios sdk class categoryviewcontroller uiviewcontroller { final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) override func viewdidload() { super viewdidload() pageevent() } func pageevent() { let myevent = pageevents(pageevents set(\["myevent"])) objpersonalization report(context pageevents, event myevent) } } page view event reports when a customer views a specified page page view event code example import uikit import monetate ios sdk class categoryviewcontroller uiviewcontroller { final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) override func viewdidload() { super viewdidload() pageevent() } func pageevent() { let myevent = pageevents(pageevents set(\["myevent"])) objpersonalization report(context pageevents, event myevent) } } product thumbnail event reports when a customer views a product thumbnail productthumbnailview event code example import uikit import monetate ios sdk class productlistviewcontroller uiviewcontroller { final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) override func viewdidload() { super viewdidload() productthumbnailviewevent() } func productthumbnailviewevent() { let productsarr = \[ "backp 001", "backp 002", "backp 003", "backp 004", "backp 005", "backp 006", "backp 007", "backp 008", "backp 009", "backp 010", ] objpersonalization report( context productthumbnailview, event productthumbnailview(products set(productsarr))) } } product detail view event reports when a customer views a product detail page productdetailview event code example import uikit import monetate ios sdk class productdetailviewcontroller uiviewcontroller { final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) override func viewdidload() { super viewdidload() productdetailviewevent() } func productdetailviewevent() { let products = \[ product(productid "product72", sku "product72 large green"), product(productid "product43", sku "product43 medium striped"), ] objpersonalization report( context productdetailview, event productdetailview(products \[products])) } } recommendation clicks event reports recommendations click events recclicks event code example import uikit import monetate ios sdk class productdetailviewcontroller uiviewcontroller { @iboutlet weak var imageview uiimageview! @iboutlet weak var titleproduct uilabel! @iboutlet weak var price uilabel! @iboutlet weak var addtocartbutton uibutton! @iboutlet weak var descriptiontextview uitextview! @iboutlet weak var reclabel uilabel! @iboutlet weak var reclineseperatorview uiview! @iboutlet weak var collectionview uicollectionview! var productobj productobj? var recproductarr \[productobj] = \[] var isrecproduct bool = false final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) override func viewdidload() { super viewdidload() self reclabel ishidden = true self reclineseperatorview\ ishidden = true self collectionview\ ishidden = true fetchrecommendations() imageview\ image = productobj? image titleproduct text = productobj? title price text = "price $\\(string(productobj! price))" collectionview\ contentinset = uiedgeinsets(top 0, left 10, bottom 0, right 10) descriptiontextview\ textcontainer linefragmentpadding = 0 descriptiontextview\ text = productobj? description adjustuitextviewheight(arg descriptiontextview) } override func viewwillappear( animated bool) { if self isrecproduct { // recording recclicks objpersonalization report( context recclicks, event recclicks(recclicks \[(self productobj? rectoken!)! as string])) } } func adjustuitextviewheight(arg uitextview) { arg translatesautoresizingmaskintoconstraints = true arg sizetofit() arg isscrollenabled = false } func fetchrecommendations() { objpersonalization addevent( context pageview, event pageview(pagetype "pdp", path "n/a", url "n/a", categories \[], breadcrumbs \[])) objpersonalization getactionsdata( requestid "123456", includereporting false, arractiontypes \["monetate\ action\ omnichannelrecommendation"] ) on { res in if res status == 200 { self handlerecommendations(res res) } else { } } } fileprivate func handlerecommendations(res apiresponse) { let data = json(res data as any) for item in data\["data"]\["responses"] arrayvalue { if item\["requestid"] string == res requestid { for oneaction in item\["actions"] arrayvalue { if oneaction\["component"] string == "ios inapp recs" { recproductarr removeall() self reclabel ishidden = false self reclineseperatorview\ ishidden = false self collectionview\ ishidden = false for productdict in oneaction\["items"] arrayvalue { for cat in categorygeneratorforproducts categories { for prdct in cat products { if prdct pid == productdict\["id"] rawvalue as! string { prdct rectoken = productdict\["rectoken"] rawvalue as? string prdct recsetid = productdict\["recsetid"] rawvalue as? double prdct affinity = productdict\[" affinity"] rawvalue as? double prdct rawaffinity = productdict\[" rawaffinity"] rawvalue as? double prdct slotindex = productdict\["slotindex"] rawvalue as? int recproductarr append(prdct) } } } } self collectionview\ reloaddata() dispatchqueue main asyncafter( deadline now() + 2 0, execute { self collectionview\ reloaddata() }) return } } } } } @ibaction func addtocartbuttonaction( sender uibutton) { var cartline \[cartline] = \[] cartline append( cartline( sku productobj! sku, pid productobj! pid, quantity productobj! quantity, currency "usd", value string(productobj! price double(productobj! quantity)))) ispageviewevent = false isaddtocartevent = true } } extension productdetailviewcontroller uicollectionviewdelegate, uicollectionviewdelegateflowlayout, uicollectionviewdatasource { func collectionview( collectionview uicollectionview, numberofitemsinsection section int) > int { return recproductarr count } func collectionview( collectionview uicollectionview, cellforitemat indexpath indexpath) > uicollectionviewcell { let cell = collectionview\ dequeuereusablecell( withreuseidentifier "pdpcollectionviewcell", for indexpath) as! pdpcollectionviewcell let recproduct = recproductarr\[indexpath row] cell productimageview\ image = recproduct image cell producttitlelabel text = recproduct title cell productpricelabel text = "$" + string(recproduct price) return cell } func collectionview( collectionview uicollectionview, didselectitemat indexpath indexpath) { let controller = uistoryboard(name "ecommerce", bundle nil) instantiateviewcontroller( identifier "productdetailviewcontroller") as! productdetailviewcontroller controller productobj = self recproductarr\[indexpath row] controller isrecproduct = true self navigationcontroller? pushviewcontroller(controller, animated false) } } recommendation impressions event reports recommendations impression events recimpressions event code example import uikit import monetate ios sdk class productdetailviewcontroller uiviewcontroller { @iboutlet weak var imageview uiimageview! @iboutlet weak var titleproduct uilabel! @iboutlet weak var price uilabel! @iboutlet weak var addtocartbutton uibutton! @iboutlet weak var descriptiontextview uitextview! @iboutlet weak var reclabel uilabel! @iboutlet weak var reclineseperatorview uiview! @iboutlet weak var collectionview uicollectionview! var productobj productobj? var recproductarr \[productobj] = \[] var isrecproduct bool = false final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) override func viewdidload() { super viewdidload() self reclabel ishidden = true self reclineseperatorview\ ishidden = true self collectionview\ ishidden = true fetchrecommendations() imageview\ image = productobj? image titleproduct text = productobj? title price text = "price $\\(string(productobj! price))" collectionview\ contentinset = uiedgeinsets(top 0, left 10, bottom 0, right 10) descriptiontextview\ textcontainer linefragmentpadding = 0 descriptiontextview\ text = productobj? description adjustuitextviewheight(arg descriptiontextview) } override func viewwillappear( animated bool) { if self isrecproduct { // recording recimpressions objpersonalization report( context recimpressions, event recimpressions(recimpressions \[(self productobj? rectoken!)! as string])) } } func adjustuitextviewheight(arg uitextview) { arg translatesautoresizingmaskintoconstraints = true arg sizetofit() arg isscrollenabled = false } func fetchrecommendations() { objpersonalization addevent( context pageview, event pageview(pagetype "pdp", path "n/a", url "n/a", categories \[], breadcrumbs \[])) objpersonalization getactionsdata( requestid "123456", includereporting false, arractiontypes \["monetate\ action\ omnichannelrecommendation"] ) on { res in if res status == 200 { self handlerecommendations(res res) } else { } } } fileprivate func handlerecommendations(res apiresponse) { let data = json(res data as any) for item in data\["data"]\["responses"] arrayvalue { if item\["requestid"] string == res requestid { for oneaction in item\["actions"] arrayvalue { if oneaction\["component"] string == "ios inapp recs" { recproductarr removeall() self reclabel ishidden = false self reclineseperatorview\ ishidden = false self collectionview\ ishidden = false for productdict in oneaction\["items"] arrayvalue { for cat in categorygeneratorforproducts categories { for prdct in cat products { if prdct pid == productdict\["id"] rawvalue as! string { prdct rectoken = productdict\["rectoken"] rawvalue as? string prdct recsetid = productdict\["recsetid"] rawvalue as? double prdct affinity = productdict\[" affinity"] rawvalue as? double prdct rawaffinity = productdict\[" rawaffinity"] rawvalue as? double prdct slotindex = productdict\["slotindex"] rawvalue as? int recproductarr append(prdct) } } } } self collectionview\ reloaddata() dispatchqueue main asyncafter( deadline now() + 2 0, execute { self collectionview\ reloaddata() }) return } } } } } @ibaction func addtocartbuttonaction( sender uibutton) { var cartline \[cartline] = \[] cartline append( cartline( sku productobj! sku, pid productobj! pid, quantity productobj! quantity, currency "usd", value string(productobj! price double(productobj! quantity)))) ispageviewevent = false isaddtocartevent = true } } extension productdetailviewcontroller uicollectionviewdelegate, uicollectionviewdelegateflowlayout, uicollectionviewdatasource { func collectionview( collectionview uicollectionview, numberofitemsinsection section int) > int { return recproductarr count } func collectionview( collectionview uicollectionview, cellforitemat indexpath indexpath) > uicollectionviewcell { let cell = collectionview\ dequeuereusablecell( withreuseidentifier "pdpcollectionviewcell", for indexpath) as! pdpcollectionviewcell let recproduct = recproductarr\[indexpath row] cell productimageview\ image = recproduct image cell producttitlelabel text = recproduct title cell productpricelabel text = "$" + string(recproduct price) return cell } func collectionview( collectionview uicollectionview, didselectitemat indexpath indexpath) { let controller = uistoryboard(name "ecommerce", bundle nil) instantiateviewcontroller( identifier "productdetailviewcontroller") as! productdetailviewcontroller controller productobj = self recproductarr\[indexpath row] controller isrecproduct = true self navigationcontroller? pushviewcontroller(controller, animated false) } } impressions event reports impression events impressions event code example import uikit import monetate ios sdk class productdetailviewcontroller uiviewcontroller { final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) override func viewdidload() { super viewdidload() recordimpressionsevent() } func recordimpressionsevent() { let impressionids = \["3 ms4xlje1mtq4mdg5mdaumdawmdaw"] objpersonalization report( context impressions, event impressions(impressionids impressionids)) } } add to cart event reports when a customer adds a product to their cart import and use the cartlinesdata interface for this event cartline is the data structure used by this interface add to cart event code example import marqueelabel import uikit import monetate ios sdk class productdetailviewcontroller uiviewcontroller { @iboutlet weak var imageview uiimageview! @iboutlet weak var titleproduct uilabel! @iboutlet weak var price uilabel! @iboutlet weak var addtocartbutton uibutton! @iboutlet weak var descriptiontextview uitextview! var productobj productobj? var quantityofproduct = 0 var cartcount = 0 var lblbadge uilabel! var isaddtocartevent bool = false final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) override func viewdidload() { super viewdidload() imageview\ image = productobj? image titleproduct text = productobj? title price text = "price $\\(string(productobj! price))" descriptiontextview\ textcontainer linefragmentpadding = 0 descriptiontextview\ text = productobj? description adjustuitextviewheight(arg descriptiontextview) let cartbtn = uibutton(type custom) cartbtn frame = cgrect(x 0, y 0, width 35, height 35) cartbtn setimage(uiimage(named "shopping cart"), for normal) cartbtn addtarget(self, action #selector(opencart), for touchupinside) self lblbadge = uilabel init(frame cgrect init(x 20, y 0, width 15, height 15)) self lblbadge backgroundcolor = miscclass hexstringtouicolor(hex "e80101") self lblbadge clipstobounds = true self lblbadge layer cornerradius = 7 self lblbadge textcolor = uicolor white self lblbadge font = uifont(name "roboto regular", size 10) self lblbadge textalignment = center cartbtn addsubview(self lblbadge) self navigationitem rightbarbuttonitems = \[uibarbuttonitem init(customview cartbtn)] addtocartbutton titlelabel? font = uifont(name "roboto regular", size 16) } override func viewwillappear( animated bool) { updatecarticon() dispatchqueue main asyncafter( deadline now() + 4 0, execute { self imageview\ image = self productobj? image }) } func adjustuitextviewheight(arg uitextview) { arg translatesautoresizingmaskintoconstraints = true arg sizetofit() arg isscrollenabled = false } func getcartcount() { var count = 0 for cat in categorygeneratorforproducts categories { for prdct in cat products { if prdct quantity > 0 { count = count + prdct quantity } } } self cartcount = count } func updatecarticon() { getcartcount() if cartcount > 0 { self lblbadge text = "\\(cartcount)" self lblbadge ishidden = false } else { self lblbadge ishidden = true } } @objc func opencart() { let stroty = uistoryboard(name "ecommerce", bundle nil) let controller = stroty instantiateviewcontroller(identifier "ecomcartviewcontroller") as! ecomcartviewcontroller self navigationcontroller? pushviewcontroller(controller, animated false) } @ibaction func addtocartbuttonaction( sender uibutton) { productobj? quantity += 1 updatecarticon() var cartline \[cartline] = \[] cartline append( cartline( sku productobj! sku, pid productobj! pid, quantity productobj! quantity, currency "usd", value string(productobj! price double(productobj! quantity)))) ispageviewevent = false isaddtocartevent = true objpersonalization getactions( requestid "123456", includereporting false, arractiontypes \["monetate\ action\ omnichanneljson"], eventsdict \[ pageview pageview( pagetype "pdp", path "n/a", url "n/a", categories \[], breadcrumbs \[]), addtocart addtocart(cartlines cartline), ] ) on { res in if res status == 200 { self handleaction(res res) } else { } } } } purchase event reports when a customer purchases products import and use the purchasedata interface for this event purchaseline is the data structure used by this interface purchase event code example import jgprogresshud import uikit import monetate ios sdk class purchaseproductviewcontroller uiviewcontroller { var productforcart \[productobj] = \[] @iboutlet weak var toplabel uilabel! @iboutlet weak var horizotalcentreview uiview! @iboutlet weak var purchasebtn uibutton! @iboutlet weak var tableview uitableview! var spinner spinnerview? var ispurchasesuccessful = false final var objpersonalization = personalization( account account( instance "p", domain "localhost org", name "a 701b337c", shortname "localhost"), user user(deviceid "62bd2e2d 213d 463f 83bb 12c0b2530a14")) override func viewdidload() { super viewdidload() tableview\ delegate = self tableview\ datasource = self tableview\ separatorstyle = none horizotalcentreview\ ishidden = true self title = "checkout" } override func viewwillappear( animated bool) { var totlaprice = 0 0 for prod in productforcart { totlaprice += prod price double(prod quantity) } toplabel text = "total price of products $\\(totlaprice)" } @ibaction func godashboard( sender any) { self navigationcontroller? poptoviewcontroller( (self navigationcontroller? viewcontrollers first)!, animated false) } @ibaction func buy( sender any) { let hud = jgprogresshud() hud textlabel text = "purchasing " hud show(in self view) hud dismiss(afterdelay 3, animated true) { \[self] in let alert = uialertcontroller( title "payment", message "would you like to proceed with payment?", preferredstyle alert ) alert addaction( uialertaction( title "yes", style default, handler { action in let hud2 = jgprogresshud() hud2 textlabel text = "payment " hud2 show(in self view) hud2 dismiss(afterdelay 3, animated true) { \[self] in placeorderdidselect() print("purchased") } })) alert addaction( uialertaction( title "no", style destructive, handler { action in })) self present(alert, animated true, completion nil) } } func placeorderdidselect() { var cartline \[purchaseline] = \[] for item in productforcart { cartline append( purchaseline( sku item sku, pid item pid, quantity item quantity, currency "usd", value string(double(item quantity) item price))) } objpersonalization addevent( context pageview, event pageview( pagetype "purchase", path "n/a", url "n/a", categories \[], breadcrumbs \[])) objpersonalization addevent( context purchase, event purchase( account "amazon", domain "amazon com", instance "temp", purchaseid "pur 23232", purchaselines cartline)) objpersonalization getactionsdata( requestid "123456", includereporting false, arractiontypes \["monetate\ action\ omnichanneljson"] ) on { (res) in self ispurchasesuccessful = true self handleaction(res res) } } fileprivate func handleaction(res apiresponse) { let data = json(res data) for item in data\["data"]\["responses"] arrayvalue { if item\["requestid"] string == res requestid { for oneaction in item\["actions"] arrayvalue { let component = oneaction\["component"] string ?? "" if component lowercased() == "footer" { if let json = oneaction\["json"] dictionary { print("final dict \\(json)") if let text = json\["text"]? string { if ispurchasesuccessful { for item in productforcart { categorygeneratorforproducts chnangequantityproduct(pid item pid, value 0) } horizotalcentreview\ ishidden = false tableview\ ishidden = true productforcart removeall() tableview\ reloaddata() purchasebtn ishidden = true toplabel ishidden = true return } } } } } } } } } extension purchaseproductviewcontroller uitableviewdelegate, uitableviewdatasource { func tableview( tableview uitableview, numberofrowsinsection section int) > int { return productforcart count } func tableview( tableview uitableview, cellforrowat indexpath indexpath) > uitableviewcell { let cell = tableview\ dequeuereusablecell(withidentifier "purchaseproducttableviewcell", for indexpath) as! purchaseproducttableviewcell cell img image = productforcart\[indexpath row] image cell name text = productforcart\[indexpath row] title cell price text = "price $\\(string(productforcart\[indexpath row] price))" cell quantiy text = "quantity \\(string(productforcart\[indexpath row] quantity))" cell totalprice text = "total price $\\(string(double(productforcart\[indexpath row] quantity) productforcart\[indexpath row] price))" cell totalprice textcolor = systemgreen cell name textcolor = systemgreen return cell } func tableview( tableview uitableview, heightforrowat indexpath indexpath) > cgfloat { return 85 } } decision event this event doesn't need to be created the sdk automatically creates a decision event when you use the sdk methods method and pass a requestid as a string and includereporting as a bool, respectively