Skip to main content

Swift SDK

See how easy it is to integrate high-performance ads into your iOS app using our lightweight SDK.

Requirements

  • iOS 14.0+
  • Swift 5.9+
  • Xcode 15+

Getting started

1. Instalation

To get started, you will need to set up a publisher account to get a publisherToken and code
Swift Package Manager and CocoaPods are two currently supported ways of integrating KontextSwiftSDK into your project. The Swift Package Manager is integrated to Swift and is one of the easiest ways to add a dependency to an iOS app. Once the Swift Package is setup add KontextSwiftSDK into your list of dependencies.
dependencies: [
    .package(url: "https://github.com/kontextso/sdk-swift", .upToNextMajor(from: "1.1.4")) /// Update to the latest version
]
Alternatively you can use Xcode’s UI: File > Add Package Dependencies ... and paste the URL into search.

CocoaPods

If you prefer CocoaPods instead. Add the following line to your Podfile:
pod 'KontextSwiftSDK'
Link to Podspec

2. Initialize AdsProvider

Once you have the dependency added and resolved you should be able to import the SDK. Next, AdsProvider, the object responsible for managing the loading and displaying ads. This is the most important part of the library. It utilizes previously created configuration.
import KontextSwiftSDK

let character = Character(
	id: '<character-id>',
    name: '<character-name>',
    avatarUrl: '<character-avatar-url>'
)

let configuration = AdsProviderConfiguration(
    publisherToken: "<publisher-token>",
    userId: "<user-id>",
    conversationId: "<conversation-id>",
    enabledPlacementCodes: ["<code>"],
    character: character,
    advertisingId: "<IDFA>",
    vendorId: "<IDFV>"
)

let adsProvider = AdsProvider(
	// Previously created configuration (it is immutable and publicly available if you need to refer to it later)
	configuration: configuration,
	// ID of the session, will be nil for new chats, SDK will resolve it internally with first ads.
	sessionId: nil,
	// Optional delegate to consume events using delegate pattern.   
    delegate: self
)
AdsProvider also exposes eventPublisher property for observing events using Combine.

3. Prepare messages

Adapt your message object to provide necessary information for the ads recommendation to work. You have two options, either make them conform to MessageRepresentable to return respective properties or to MessageRepresentableProviding and return the MessageRepresentable as a whole new object. There is struct AdsMessage: MessageRepresentable which you can use for this scenario.
// 1. Option: Conformance to MessageRepresentable
struct MyChatMessage: MessageRepresentable {
	...
	/// Unique ID of the message
	var id: String { self.uuid.uuidString }
	/// Role of the author of the message (user or assistant)
	var role: Role { self.isUser ? .user : .assistant }
	/// Content of the message
	var content: String { self.messageContent }
	/// Timestamp when the message was created
	var createdAt: Date { self.date }
	...
}

// 2. Option: Conformance to MessageRepresentableProviding
// Better if you have collision of names of properties
struct MyChatMessage: MessageRepresentable {
	...
	var message: MessageRepresentable {
		AdsMessage(
			id: self.uuid.uuidString,
			role: self.isUser ? .user : .assistant,
			content: self.messageContent,
			createdAt: self.date
		)
	...	
}
Whenever your list of messages changes you need to pass the new list to AdsProvider.
adsProvider.setMessages(messages)

4. Show your first ad

The last thing remaining is to provide place for the Ads to manifest into. This is done by placing InlineAdView into View hierarchy just after the associated message. The view will take care of loading the ad.
@State private var ads: [Advertisement] = []

ZStack {
    ForEach(messages, id: \.uuid.uuidString) { message in
        VStack {
            MyChatMessageView(message)
      
            if let ad = ads.first, ad.messageId == message.id {
				// Display advertisement
            	InlineAdView(ad: ad)
			}
        }
    }
}.onReceive(adsProvider.eventPublisher) { event in
   // React to adsProvider events
	switch event {
    case .filled(let newAds):
        ads = newAds
    case .adHeight(let newAd):
        guard let index = ads.firstIndex(where: { $0.id == newAd.id }) else {
            return
        }

        ads[index] = newAd
    default:
        break
    }	
}
For usage with UIKit please use InlineAdUIView instead and refer to the ExampleUIKit app.

API documentation

AdsProvider properties

configuration
AdsProviderConfiguration
required
The configuration of the AdsProvider.
sessionId
string
Session ID representing the current user session. If not provided, a new session ID will be generated.
isDisabled
boolean
If true, the ads generation will be disabled initially. Can be later enabled by calling enable().
delegate
AdsProviderDelegate
Delegate to receive ads related updates. Called on a main thread.

AdsProviderConfiguration properties

publisherToken
string
required
Your unique publisher token.
userId
string
required
Unique identifier that remains the same for the user’s lifetime (used for retargeting and rewarded ads).
conversationId
string
required
Unique ID of the conversation.
enabledPlacementCodes
array
required
Placement codes enabled for the conversation. Example: ['inlineAd'].
character
object
required
Character object used in this conversation.
variantId
string
Publisher-provided identifier for the user cohort (for A/B testing).
advertisingId
string
Device-specific identifier provided by the operating systems (IDFA).
vendorId
string
Vendor-specific identifier provided by the operating systems (IDFV).
regulatory
object
Regulatory object used in this conversation.
otherParams
dictionary
An arbitrary key-value collection of values that the publisher can send. It varies per publisher, but all publishers provide at least the theme parameter.

InlineAdView & InlineAdUIView properties

advertisement
object
Advertisement object describing the ad.

AdsEvent types

filled

The ad is available or ads have changed.
ads
array
required
Available advertisements.

noFill

adHeight

The height of a specific ad has been updated.
ad
Advertisement
required
Advertisement whose height has changed after render.

viewed

The user has viewed the ad.

clicked

The user has clicked the ad.

renderStarted

Triggered before the first token is received.

renderCompleted

Triggered after the last token is received.

error

Triggered when an error occurs.

videoStarted

Triggered when the video playback starts.

videoCompleted

Triggered when the video playback finishes.

rewardGranted

Triggered when the user receives a reward.

event

Any other event. Payload is a dictionary.

Guides

Controlling when ads load

You can fine-tune ad frequency by controlling when new messages are passed into AdsProvider. This allows you to adjust the ratio of ads to messages dynamically.

Handling no-fill events

You get notified when the ad is not available by subscribing to the noFill event.

Sizing the ad

Especially when using UIKit, the ad inside of UITableView or UICollectionView needs to be sized properly to be displayed correctly. You get notified about ad height changes by subscribing to the adHeight event. Size changes multiple times as the ad gets rendered and ultimately stops at the final height.
I