Setting up Xcode Project
First, we need to create a new Xcode project. Open Xcode and select "File" > "New" > "Project." Choose the "iOS App" template and select "SwiftUI" as the User Interface. Give your project a name and select a location to save it.
Building the Chat UI
Hey, hi, hello! We will use SwiftUI's built-in components to build the chat UI. First, we'll create a new file called "ChatView.swift" and add it to the project. In this file, we'll define a struct called "ChatView" which will be our root view. We'll use a LazyVStack to arrange the views vertically and a List to display the messages.
We'll then add our Textfield to write our message and a Button to be able to send it. We'll also connect the 'return' function of our Textfield to be able to send the message as well.
Creating an OpenAI Account
In order to use OpenAI's completions API, we need to create an account on their website. Go to the OpenAI website, head to the API and sign up.
Getting OpenAI API Key
Once you have an account, you can generate an API key. Click on your account in the top right corner, select "View API Keys", and generate a new secret. Copy the API key, store it somewhere safe and avoid sharing it with anyone.
Storing Key in Constants
To keep our API key secure, we will store it in a constant. Create a new file called "Constants.swift" and add it to the project. In this file, we'll define an enum called "Constants" and add a constant called "openAIApiKey" which stores our API key.
Making the Requests
To make requests to the OpenAI API, we'll use the Alamofire library. We'll be importing it as a Swift Package, however you can also use Cocoapods or other dependency managers. Go to the project settings, select your target and click "Swift Packages" and then "+" button, to add the library.
To keep our UI code clean from as much logic as possible, we'll create an OpenAIService class, which will handle making our requests, and relay that information back to our UI using Combine.
We'll make sure the class has the base URL and a function to send our message.
Since our request is a POST request, we'll create a body struct called OpenAICompletionsBody. The body will take in the following parameters:
- model: the OpenAI language model (we'll be using "text-davinci-003")
- prompt: the message we'd like to send to the API
- temperature: how random/determinative the responses should be between 0 and 1 (with 1 being most random and least deterministic)
- max_tokens: the maximum number of tokens our response should contain
For more information on this API, head to OpenAI API
We'll also create a response object called OpenAICompletionsResponse.
Next, we'll build our request in the "sendMessage" function of our OpenAIService. Lets start off with the body and our headers which will contain our API key. We'll also import the Combine framework to be able to return a publisher.
Next, we want to return make our request using a Combine publisher - we'll add the return to our function and create a Future which will make our request.
Make sure we pass in the body, the url and the headers to our request. We'll also make use of the Swift Result to send back our response
Connecting the UI and Service
Now that we've build our service and the UI, now it's time to connect it all up. We're going to jump back into our ChatView.swift file, and create a ChatMessage struct, and a sender enum to track who sent the message. This will allow us to handle our styling appropriately for each message.
Than declare an instance of the OpenAIService, create an empty state array of messages, and an AnyCancellable set to store our publisher (don't forget to import Combine).
Below our view's body, we'll create a messageView ViewBuilder function for the UI of each message. We'll style the messages conditionally and use a Spacer on either side to nudge the content based on the sender.
Add the messageView to the body within the List.
To wrap it all up, we're going to finish off the 'sendMessage' function in our ChatView for when we tap 'return' or the 'send' button. When we send a message, we're going to create a ChatMessage and append that to the message. We'll then make an API request to OpenAI using the input text, then clear the input text.
All that's left is to subscribe to the publisher in our 'sendMessage' function, and add the message that's received to our array.
You're all set and should start being able to send message through the Chat UI. Feel free to style the messages and the interface however you like to bring your app to life and take the experience to the next level.
If you have any questions, feel free to send them through to my socials as I'll be more than happy to help! ✌️