Moments
Mobile
iOS Integration Guide (Swift)
22min
this guide shows you how to integrate the momentscience sdk into your ios app using swift the sdk supports two prefetch modes, each designed to improve the checkout experience by preloading relevant offers in advance integration modes sdk prefetch mode this is the lightest and fastest integration method a hidden 0Γ0 webview is embedded on a screen before checkout (such as the cart) this webview loads the momentscience sdk, which prefetches and caches available offers in the background at checkout, offers are displayed instantly using the cached data requires minimal native logic no manual network calls api prefetch mode this mode gives your app full control over the offer fetching process it performs a native https request to fetch offers before initializing the sdk the sdk is loaded at checkout using the response payload provided by your app full control over timing and parameters for offer fetching customize request details (e g , user id, cart total, session id) in both modes, offers are rendered in a webview at the checkout screen because offers are preloaded before checkout, the user experience remains fast and frictionless, even when no offers are found if no offers are returned, you can choose to skip showing the offer display screen altogether requirements to integrate the momentscience sdk into your ios app, ensure the following prerequisites are met momentscience sdk id learn more about getting your sdk id environment swift version 5 ui framework swiftui minimum ios version 15 6 setup instructions step 1 add dependencies add html assets the momentscience sdk uses local html files to render offers in a webview these must be added to your xcode project required files webpage template html https //github com/adspostx/examples/blob/main/ios native/momentsapiwebdemoapp/momentsapiwebdemoapp/webpage template html prefetch template html https //github com/adspostx/examples/blob/main/ios native/momentsapiwebdemoapp/momentsapiwebdemoapp/prefetch template html you can place these files anywhere in your xcode project, in the momentscience ios demo app , they are added to the root of the project add and install dependencies the momentscience demo app does not rely on any third party libraries however, since offers are rendered in a webview, make sure to import the webkit framework to use webview importing webkit import webkit this allows the app to load and display offer experiences powered by the momentscience sdk step 2 prefetch offers (sdk or api) you can prefetch offers using one of two modes sdk prefetch uses a hidden 0Γ0 webview to silently fetch and cache offers before checkout api prefetch uses a native api call to fetch offers, which are then injected into the sdk display template in both modes, you can skip showing the checkout screen if no offers are found option 1 sdk prefetch this approach uses a hidden webview to load the momentscience web sdk in prefetch mode when offers are found, the sdk sends an ads found event to your app itβs the lightest touch integration, ideal when you want minimal native logic step 1 load the web sdk in a 0Γ0 webview to prefetch offers choose a screen that appears before the checkout (e g , the cart) add a hidden 0Γ0 webview that loads the sdk and initiates prefetching make sure to enable java script for webview π example implementation in swiftui 2\ implement message handling to listen for sdk events use the wkscriptmessagehandler to capture events or payloads returned by the sdk func usercontentcontroller( usercontentcontroller wkusercontentcontroller, didreceive message wkscriptmessage) this callback is triggered when the sdk completes prefetching use it to determine whether offers are available example implementation of wkscriptmessagehandler 3\ load the webview using a pre filled html template do { let htmlcontent = try viewmodel generateprefetchhtml() webview\ loadhtmlstring(htmlcontent, baseurl viewmodel baseurl) } catch { print("failed to load html template \\(error)") } generateprefetchhtml() replaces placeholders in prefetch template html with real values sdkid , payload , and adpxuser the html file contains javascript to load the sdk in prefetch mode step 2 show offers using fullscreen webview once offers are prefetched and confirmed to be available, render them in a fullscreen webview on the checkout screen use a navigationlink (or your preferred navigation mechanism) to transition to the screen that displays the offers/checkout screen, pass required parameters as below navigationlink( destination webpageview( sdkid viewmodel sdkid, momentsapiresponse viewmodel checkoutapiresponse, loadmode viewmodel prefetching ?? prefetchapi, offercount viewmodel offerscount, userpayload viewmodel userpayload ) ) \| π fullscreen webview implementation 2\ the webpageview uses a full screen wkwebview to load html with the sdk and preloaded offer content make sure to enable java script for wkwebview |π view webpageviewmodel swift implementation webview\ loadhtmlstring(htmlcontent, baseurl baseurl) offers are embedded into a template before rendering the sdkid, offerdata, payload are injected via htmlcontent in the viewmodel it replaces placeholders in the base html file before loading into the webview π template logic references webpageviewmodel swift webpage template html option 2 prefetch with api in this method, your app fetches offers from the momentscience offers api ahead of time and passes them into the web sdk at render time step 1 fetch offers via momentscience offers api send a post request to the offers api | π example networkservice swift post https //api adspostx com/native/v4/offers json do { // call the network service to fetch offers let response = try await networkservice fetchoffers( sdkid sdkid, ua useragent, placement nil, ip nil, adpxfp adpxfp, dev "1", subid nil, pubuserid adpxfp, payload userpayload, loyaltyboost nil, creative nil ) momentsapiresponse = response showcheckout = hasoffers } catch { // handle any errors from the api call } save the json response in your view model or local state so it can be injected into the web sdk later step 2 show offers in fullscreen webview once offers are confirmed, render them inside a full webview by passing the prefetched data into your offer display/checkout screen make sure to enable java script for webview navigate to the offer screen using swiftuiβs navigationlink and provide the necessary parameters | πexample offersview\ swift navigationlink( destination webpageview( sdkid viewmodel sdkid, momentsapiresponse viewmodel checkoutapiresponse, loadmode viewmodel prefetching ?? prefetchapi, offercount viewmodel offerscount, userpayload viewmodel userpayload ) ) display the sdk in webview example webpageviewmodel swift make sure to enable java script for webview webview\ loadhtmlstring(htmlcontent, baseurl baseurl) inject offer data using a template the webpageviewmodel prepares the html using htmlcontent this method loads webpage template html replaces placeholders like sdkid , payload , momentsapiresponse , and window\ adpxuser with actual runtime values step 3 open links in an external browser to ensure links inside the web sdk (e g , offer ctas) open in the userβs default browser instead of within your webview, you need to override default webview behavior using wknavigationdelegate , wkuidelegate , and wkscriptmessagehandler example webpageview\ swift intercept navigation events implement wknavigationdelegate to evaluate and selectively allow or block url navigation func webview( webview wkwebview, decidepolicyfor navigationaction wknavigationaction, decisionhandler @escaping (wknavigationactionpolicy) > void) { if let url = navigationaction request url { decisionhandler(viewmodel shouldopenurl(url) ? allow cancel) } else { decisionhandler( allow) } } handle new window requests implement wkuidelegate to intercept links that attempt to open in a new window and instead launch them externally func webview( webview wkwebview, createwebviewwith configuration wkwebviewconfiguration, for navigationaction wknavigationaction, windowfeatures wkwindowfeatures) > wkwebview? { if let url = navigationaction request url, viewmodel shouldopenurl(url) { viewmodel openexternal(url url) } return nil } handle javascript initiated events the web sdk may dispatch javascript events (e g , offer clicks) using postmessage to receive and respond to these, implement wkscriptmessagehandler func usercontentcontroller( usercontentcontroller wkusercontentcontroller, didreceive message wkscriptmessage ) { if message name == "adpxcallback", let messagedict = message body as? \[string any], let event = messagedict\["event"] as? string, let payload = messagedict\["payload"] as? \[string any] { viewmodel handlemessage(event event, payload payload) } } in handlemessage , check for the " url clicked " event type extract the target url and open it using uiapplication shared open(targeturl) example webpageviewmodel swift check out the momentscience ios demo on github to see the complete implementation, including offer fetching, webview rendering, event handling, and external link support conclusion congratulations! you've successfully integrated the momentscience sdk into your ios app using swift and swiftui whether youβre using sdk prefetch mode or api prefetch mode, your app is now equipped to deliver personalized offers directly within the user experience this setup enables dynamic monetization while preserving control over when and how offers are displayed π’ if you're running into any issues while going through the integration process, feel free to contact us at help\@m omentscience com