Integrate SAP Conversational AI Chatbot into your iOS application
- How to create a mobile channel for your chatbot in SAP Conversational AI
- How to create a destination in SAP Mobile Services to proxy requests from your iOS application to your chatbot in SAP Conversational AI
- How to integrate the open-source SAP Conversational AI SDK for iOS into an existing iOS application generated with the SAP BTP SDK for iOS Assistant
Prerequisites
- You have created a SAP Conversational AI chatbot, for example, as described in the tutorial Build Your First Chatbot with SAP Conversational AI
- You have generated a sample iOS application as described in the tutorial Create a Sample iOS App
- Step 1
Sign-in to your bot on https://cai.tools.sap/ and perform the following steps in the Connect tab:
-
Click the
+
button.A modal popup opens.
-
Enter
Name
andApplication ID
. -
Click
Create
, then copyName
and the generatedChannel ID
andToken
to reuse later.
Log in to complete tutorial -
- Step 2
-
Access
Tokens
through your bot’sSettings
. -
Click
Generate
to create the OAuth client Runtime API. -
Choose
Client Credentials
. -
Close the confirmation dialog.
-
Copy the generated
Auth URL
,Client ID
andClient Secret
to reuse later.
Log in to complete tutorial -
- Step 3
-
Click on
Mobile Connectivity
in your application definition. -
Click the
+
button to start the destination create wizard. -
In Basic Info enter the required
Destination Name
andURL
.Field Value Destination Name CAI
URL https://sapcai-community.sapcai.eu10.hana.ondemand.com/public/api
Note: Outside of this tutorial, you are free to choose any name for your destination. The URL is different and tenant-specific if you use SAP Conversational AI Enterprise Edition but the suffix
/public/api
is always needed.Click Next.
-
Click Next on Custom Headers.
-
Click Next on Annotations.
-
In Destination Configuration select
OAuth2 Client Credentials
for SSO mechanism.Note: Destination and SSO Mechanism depend on the edition type of SAP Conversational AI as well as the deployment scenario. Read Enterprise Configuration guide to understand when to use other SSO mechanism types.
Enter the required
Token Service URL
,Client ID
andClient Secret
by reusing the information from Step 2.Field Value SSO Mechanism OAuth2 Client Credentials
Token Service URL https://sapcai-community.authentication.eu10.hana.ondemand.com/oauth/token
Client ID Your bot's Client ID (generated in Step 2)
Client Secret Your bot's Client Secret (generated in Step 2)
Note:
Token Service URL
is namedAuth URL
in SAP Conversational AI.Click Next.
-
Click Finish.
-
Click
Ping
to test if the destination can reach its target.
-
- Step 4
-
Open your Xcode project.
-
In Xcode menu select File > Add Packages… which opens a modal dialog.
-
Paste the following URL into the search field:
https://github.com/SAP/cloud-sdk-ios-cai
-
Click “Add Package”.
-
Select Package Product
SAPCAI-requiresToEmbedXCFrameworks
. -
Click “Add Package”.
Note: You chose Package Product
SAPCAI-requiresToEmbedXCFrameworks
because your app already embedsSAPCommon
andSAPFoundation
binary frameworks. You would select package productSAPCAI
if you did not already embed binary frameworks from SAP BTP SDK for iOS.What are the Package Products offered by SAP Conversational AI SDK for iOS?
Log in to complete tutorial -
- Step 5
It is finally time to use APIs from the SAP Conversational AI SDK for iOS. Let’s create a new file named
AssistantViewManager.swift
.Copy & paste the following code into the newly created file.
SwiftCopyimport SAPCAI import SAPFoundation import SAPFioriFlows import SwiftUI class AssistantViewManager { static let shared = AssistantViewManager() var viewModel: MessagingViewModel? var dataPublisher: CAIConversation? func createDemoBotAssistantView() -> UIViewController { let serviceConfig = CAIServiceConfig( urlSession: OnboardingSessionManager.shared.onboardingSession!.sapURLSession, host: OnboardingSessionManager.shared.onboardingSession!.settingsParameters!.backendURL.appendingPathComponent("CAI") // name of your destination created in Step 3 ) let caiChannel = CAIChannel( id: "Replace with Channel ID from Step 1", token: "Replace with Token from Step 1", slug: "Replace with Name from Step 1") self.dataPublisher = CAIConversation( config: serviceConfig, channel: caiChannel, messageDelivery: PollMessageDelivery(channelToken: caiChannel.token, channelId: caiChannel.id, serviceConfig: serviceConfig)) self.viewModel = MessagingViewModel(publisher: dataPublisher!) return UIHostingController(rootView: AssistantView() .navigationBarTitle(Text("Chat"), displayMode: .inline) .environmentObject(viewModel!) .environmentObject(ThemeManager.shared)) } func cleanup() { viewModel?.cancelSubscriptions() dataPublisher?.resetConversation() viewModel = nil dataPublisher = nil } }
You created class
AssistantViewManager
which is accessible as a singleton through itsshared
property.Some explanations about the code:
- You imported the
SAPCAI
module because this is the module of the added Swift Package. - You imported the
SwiftUI
framework because you will use SwiftUI view(s) provided by the added Swift Package. - You imported
SAPFoundation
andSAPFioriFlows
because you are reusing its classes, especiallySAPURLSession
which is fully configured to make network requests towards your SAP Mobile Service account once the user onboarded in the app. - You initialized
CAIServiceConfig
so that SAP Conversational SDK for iOS can make network requests to the destination in SAP Mobile Services created in Step 3. - You need to replace the initializer parameters of
CAIChannel
with the actual values from Step 1 ! - You used
AssistantView
which is the main reusable SwiftUI component provided by the added Swift Package. The SwiftUI view will render messages of your user’s conversation with your chatbot. - You are wrapping
AssistantView
withUIHostingController
to use it in your UIKit-based application.
Next, in
ESPMContainerCollectionsViewController.swift
add the following code at the end of functionviewDidLoad
.SwiftCopyself.navigationItem.setRightBarButton(UIBarButtonItem(barButtonSystemItem: .compose, target: self, action: #selector(self.startConversation)), animated: true)
This code adds a right bar button to invoke a function
startConversation
which you will create now. Add the following functions to classESPMContainerCollectionsViewController
.SwiftCopy// MARK: - SAPCAI integration @objc func startConversation() { present(vc: AssistantViewManager.shared.createDemoBotAssistantView()) } func present(vc: UIViewController) { let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil) let rightNavigationController = mainStoryBoard.instantiateViewController(withIdentifier: "RightNavigationController") as! UINavigationController rightNavigationController.viewControllers = [vc] self.splitViewController?.showDetailViewController(rightNavigationController, sender: nil) }
Add the following code at the end of function
viewDidAppear(_ animated: Bool)
.SwiftCopyAssistantViewManager.shared.cleanup()
That code ensures that polling of conversation updates will stop once the user navigates away from the
AssistantView
.Which is the reusable SwiftUI view, provided by the SAP Conversational AI SDK for iOS, to render a conversation natively?
Log in to complete tutorial - You imported the
- Step 6
You are now ready to test your iOS application and initiate a conversation with your chatbot.
-
In Xcode, press
⌘R
to run your application in the iOS simulator. -
Touch on the row in the
ODataContainers
view. -
Touch on the right bar button.
-
Touch the input field on the bottom to open the keyboard.
-
Enter a message and touch the send button on the bottom right.
-
Verify that your chatbot responded appropriately.
Log in to complete tutorial -