Basic integration with SwiftUI
iOS Web - Basic integration with SwiftUI
This page describes how to integrate Taboola iOS Web when using SwiftUI.
While reading the documentation, take a look at our Sample App.
This integration requires you to connect JavaScript code (in your web content) with native application code.
Initialize Taboola
The initialization steps in this section are the same for Classic and Web integrations.
In your SwiftUI app's main struct, create a TBLPublisherInfo
object and initialize Taboola:
import SwiftUI
import TaboolaSDK
@main
struct YourApp: App {
init() {
// Initialize a TBLPublisherInfo instance with your unique 'publisherName' and 'appStoreId':
let publisherInfo = TBLPublisherInfo(publisherName: "<publisherName>", appStoreId: <appStoreId>)
// Initialize Taboola for your application:
Taboola.initWith(publisherInfo)
// (Optional) Set *global* feature flags:
Taboola.setGlobalExtraProperties(["<feature flag key>":"<value>"])
// (Optional) Set the desired log level:
Taboola.setLogLevel(.LogLevelDebug)
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Params
publisherName
- An alphanumeric string, provided by Taboola - e.g."sdk-tester-demo"
.This field is also referred to as the Publisher ID.
appStoreId
- Your App Store ID, obtained via the App Store Connect dashboard.See below.
appStoreId
Your App Store ID - aka Apple ID or iTunes ID - is a unique, numeric identifier that allows Apple to distinguish your app from others.
Passing the
appStoreId
param allows for improved tracking and attribution and is strongly recommended.
Obtaining your App Store ID
- Log in to the App Store Connect dashboard.
- Under
My Apps
, select the relevant app.- Under
General
, selectApp Information
(left).- Copy your Apple ID (right).
Initialize Taboola in your app's
init()
method - or as early as possible within the app lifecycle.
Add Taboola JS tags
- Add the following meta tag to the section of your web content:
<meta name='viewport' content='width=device-width, user-scalable=no'/>
- Add the following JS tag to the section of your web content, and edit the default text:
<script type="text/javascript">
window._taboola = window._taboola || [];
_taboola.push({page_type:'auto', url:'page_url'});
!function (e, f, u, i) {
if (!document.getElementById(i)){
e.async = 1;
e.src = u;
e.id = i;
f.parentNode.insertBefore(e, f);
}
}(document.createElement('script'),document.getElementsByTagName('script')[0],
'https://cdn.taboola.com/libtrc/publisher_id/mobile-loader.js',
'tb_mobile_loader_script');
</script>
Editing instructions:
Default text | Instructions | Notes |
---|---|---|
page_type | Replace this with the relevant page type (as provided by Taboola - e.g. article ):article:'auto' | Possible values:video , article , photo , search , category , home . |
'auto' | To obtain an automated ID, leave this param as is:article:'auto' Else, insert your own, internal ID: article:'123' | Specifies the ID of this page, for the given page type. |
'page_url' | Insert the canonical web URL of the page:url:'https://www.example.com/articles?id=123' | Required so that Taboola can crawl the page for metadata and contextual data. |
publisher_id | Insert your Publisher ID (as provided by Taboola - e.g. '<<publisherID>>' ) into the URL:'https://cdn.taboola.com/libtrc/<<publisherID>>/mobile-loader.js' |
- For each placement, add the following JS tag to the of your web content, and edit the param values:
<div id="<<containerId>>"></div>
<script type="text/javascript">
window._taboola = window._taboola || [];
_taboola.push({mode: 'mode-here',
container: 'container-id-here',
placement: 'placement-here',
target_type: '<<targetType>>'});
// Notice - this part is unique to mobile SDK JS integrations!
_taboola["mobile"] = window._taboola["mobile"] || [];
_taboola["mobile"].push({
publisher:'publisher-id-here'
});
_taboola.push({
flush: true
});
</script>
Params
mode
- The UI Mode ID of the placement, as provided by Taboola - e.g.'<<mode>>'
.container
- The ID of your HTML element that contains the Taboola content - e.g. '<<containerId>>
'.placement
- The placement name, as provided by Taboola - e.g.'<<placementName>>'
.target_type
- The target type, as provided by Taboola - e.g.'<<targetType>>'
.publisher
- Your Publisher ID (aka Account ID) - a unique, alphabetic string, as provided by Taboola - e.g.'<<publisherID>>'
.
Build Taboola content instances
Guidelines
- The goal is to wrap your web view with Taboola services for event handling and management.
- For each page, initialize 1
TBLWebPage
instance, and create 1TBLWebUnit
instance only.These are used to manage the
WebView
and handle events.- Each placement is implemented via a JS tag (not via a
TBLWebUnit
instance).These JS tags inject Taboola content into your own content.
- Import the required modules:
import SwiftUI
import TaboolaSDK
import TaboolaSDK_SwiftUI_Umbrella
- Create a page wrapper to manage Taboola content:
class WebPageWrapper: NSObject, WebPageWrappable {
var page: TBLWebPage!
override init() {
super.init()
page = TBLWebPage(delegate: self)
page.pageExtraProperties = ["testWebKey":"testWebValue"]
}
}
extension WebPageWrapper: TBLWebPageDelegate {
func webView(_ webView: WKWebView!,
didClickPlacementName placementName: String!,
itemId: String!,
clickUrl: String!,
isOrganic organic: Bool) -> Bool {
// Return 'true' for Taboola SDK to handle the click event (default behavior).
// Return 'false' to handle the click event yourself. (Applicable for organic content only.)
return true
}
func webView(_ webView: WKWebView!, didLoadPlacementName placementName: String!, height: CGFloat) {
print(String(describing: placementName))
}
func webView(_ webView: WKWebView!,
didFailToLoadPlacementName placementName: String!,
errorMessage error: String!) {
print(error.debugDescription)
}
}
- Use the
WebUnitSwiftUI
wrapper in your SwiftUI view:
struct TaboolaWebView: View {
private let pageWrapper = WebPageWrapper()
var body: some View {
VStack {
if let baseURL = URL(string: "https://cdn.taboola.com/mobile-sdk/init/") {
WebUnitSwiftUI(pageWrapper: pageWrapper,
source: "SampleHTMLPage",
baseURL: baseURL)
} else {
Text("No content to display. Please check your URL!")
}
}
}
}
Params
pageWrapper
- TheWebPageWrapper
instance that manages the Taboola page.source
- The name of your HTML file (without extension) or web URL.baseURL
- The base URL for loading web content.
A complete example
Select/deselect the Swift tab to expand/collapse the sample code.
import SwiftUI
import TaboolaSDK
import TaboolaSDK_SwiftUI_Umbrella
class WebPageWrapper: NSObject, WebPageWrappable {
var page: TBLWebPage!
override init() {
super.init()
page = TBLWebPage(delegate: self)
page.pageExtraProperties = ["testWebKey":"testWebValue"]
}
}
extension WebPageWrapper: TBLWebPageDelegate {
func webView(_ webView: WKWebView!,
didClickPlacementName placementName: String!,
itemId: String!,
clickUrl: String!,
isOrganic organic: Bool) -> Bool {
// Insert your code here...
// Return 'false' if you are handling the click event yourself, or 'true' if you want Taboola SDK to handle the click event.
// Note: you can override the default behavior for *organic* content only.
return true
}
func webView(_ webView: WKWebView!, didLoadPlacementName placementName: String!, height: CGFloat) {
print("Loaded placement: \(placementName ?? "unknown")")
}
func webView(_ webView: WKWebView!,
didFailToLoadPlacementName placementName: String!,
errorMessage error: String!) {
print("Failed to load placement: \(placementName ?? "unknown") - \(error ?? "unknown error")")
}
}
struct TaboolaWebView: View {
private let pageWrapper = WebPageWrapper()
var body: some View {
VStack {
if let baseURL = URL(string: "https://cdn.taboola.com/mobile-sdk/init/") {
WebUnitSwiftUI(pageWrapper: pageWrapper,
source: "SampleHTMLPage",
baseURL: baseURL)
} else {
Text("No content to display. Please check your URL!")
}
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
TaboolaWebView()
.navigationTitle("My Web App")
}
}
}
Additional examples
See our Sample App for complete implementations using the Taboola SwiftUI Umbrella package:
- WebVStack.swift - Basic VStack integration
- WebPageView.swift - Page view integration
- WebRootView.swift - Navigation and layout structure
Guidelines
- To maintain a smooth user experience, fetch Taboola content as soon as the view appears.
- Do not cache Taboola content. Fetch new content each time the app opens, or the relevant screen is created.
- Use the same
WebPageWrapper
instance for multiple placements on the same page to optimize performance.
The click event
You can handle Taboola events by implementing the TBLWebPageDelegate
protocol in your WebPageWrapper
:
extension WebPageWrapper: TBLWebPageDelegate {
func webView(_ webView: WKWebView!,
didClickPlacementName placementName: String!,
itemId: String!,
clickUrl: String!,
isOrganic organic: Bool) -> Bool {
// Insert your code here...
// Return 'false' if you are handling the click event yourself, or 'true' if you want Taboola SDK to handle the click event.
// Note: you can override the default behavior for *organic* content only.
return true
}
}
You can override the default behavior for organic content only.
For more information, see Event Handling and didClickPlacementName.
Working with UIPageViewController
When working with UIPageViewController
, make sure to fetch Taboola content when the next page is visible to the user (not before).
- For each JS tag in the of your web content, add
lazyFetch: true
:
<script type="text/javascript">
...
_taboola["mobile"].push( {
lazyFetch: true // If you are using a `UIPageViewController`
});
</script>
- Because you added a
lazyFetch
directive within the JS tag, you must fetch Taboola content via your view controller:
// Invoke *once only*, from within `onAppear`:
pageWrapper.page.fetchAllUnitsContent() // When using `UIPageViewController`
UIPageViewController
If you prefetch more than 1 page using
UIPageViewController
:
- Fetch Taboola content when the next page is visible to the user - i.e. in the
onAppear
method.- Fetch content once only (not every time the
onAppear
method is fired).
Dark Mode
Dark mode is not supported by default. For dark-mode placements, contact your Taboola Account Manager.
Once Taboola has configured your dark-mode placements, you can use the following code in your application:
pageWrapper.page.pageExtraProperties = ["darkMode":"true"]
Well Done!
You have completed the basic integration steps using the Taboola SwiftUI Umbrella package!
If everything is working smoothly, take a look at the What's Next section below.
Taboola content not rendering?
- Test with the same params as the sample app, and see if those work.
- Still stuck? Submit a question In our forum.
What's next?
- For handling clicks and other important events, see Event Handling.
- In order to provide personalized recommendations for impressions in the EU and California, make sure to implement GDPR and CCPA respectively.
- If you have not already done so, make sure to look at our sample app.
- Once you are complete, submit your app for review - see the App Verification section.
IMPORTANT
Prior to launch, you must provide Taboola with a test app for verification. Skipping this step may result in a significant loss of revenue.
See: App Verification
Updated 16 days ago