back to tutorials

Integrating AI Widget with iOS using SwiftUI

This guide will walk you through the process of embedding the AI Widget in an iOS app using SwiftUI and WebKit.

Embedding the AI Widget Frame

To embed the AI Widget frame in your iOS app using SwiftUI, you'll need to use the WebView component provided by the WebKit framework.

First, add the following import statement at the top of your SwiftUI view file:

Next, create a WebView struct that conforms to the UIViewRepresentable protocol:

Now, you can use the WebView in your SwiftUI view to display the AI Widget frame:

In this example, the AI Widget frame is displayed when the "Show AI Widget" button is tapped, setting the showWidget state variable to true.

Advanced Integration

Setting Client-Side Functions

To set client-side functions for the AI Widget, you'll need to use the postMessage protocol. Here's an example of how to set functions:

In this example, the setFunctions() method is called when the WebView appears. It prepares the function configurations, converts them to a JSON string, and then injects a JavaScript script into the WebView to send the postMessage event to the AI Widget frame.

Make sure to replace {WIDGET_ID} with your actual widget ID in the widgetUrl.