Build ChatGPT for iOS with SwiftUI

Author Image

Mazen Kourouche

Jan 18, 2023

Building ChatGPT App in SwiftUI Cover Photo

ChatGPT has taken the internet by storm for good reason - the technology is truly powerful. In this tutorial, we'll be building our own version of ChatGPT on iOS with SwiftUI. You'll learn how to build the chat UI, handle interaction with the OpenAI API, and parse the JSON response. By the end of this tutorial, you'll have a functional chat app that can understand natural language and generate quality content.


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.

import SwiftUI

struct ChatView: View {
    var body: some View {
        LazyVStack {
            List {
                // messages go here
            }
        }
    }
}

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.

struct ChatView: View {
    var body: some View {
        ...
        HStack {
          TextField("Enter your message", text: $inputMessage) {
            sendMessage()
          }
          Button {
            sendMessage()
          } label: {
            Text("Send")
          }
    }

    func sendMessage() {
      // Handle message login here
    }
}

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.

enum Constants {
    static let openAIApiKey = "YOUR_API_KEY"
}

Making the Requests

Importing Alamofire

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.

https://github.com/Alamofire/Alamofire.git

OpenAI Service

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.

import Alamofire

class OpenAIService {
    let baseUrl = "https://api.openai.com/v1/"

    func sendMessage(message: String) {
        // Make request here
    }
}

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.

struct OpenAICompletionsBody: Encodable {
    let model: String // The language model
    let prompt: String // The message we want to send
    let temperature: Float?
    let max_tokens: Int?
}

struct OpenAICompletionsResponse: Decodable {
    let id: String
    let choices: [OpenAICompetionsChoice]
}

struct OpenAICompetionsChoice: Decodable {
    let text: String
}

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.

import Combine

class OpenAIService {
    ...

    func sendMessage(message: String) {
        let body = OpenAICompletionsBody(
            model: "text-davinci-003", 
            prompt: message, 
            temperature: 0.7, 
            max_tokens: 256
        )

        let headers: HTTPHeaders = [
            "Authorization": "Bearer \(Constants.openAIAPIKey)"
        ]

        // Make request here
    }
}

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:

func sendMessage(message: String) -> AnyPublisher<OpenAICompletionsResponse, Error> {
    ...

    return Future { [weak self] promise in
        guard let self = self else { return }

        AF.request(
          self.baseUrl + "completions", 
          method: .post, 
          parameters: body, 
          encoder: .json, 
          headers: headers
        ).responseDecodable(of: OpenAICompletionsResponse.self) { response in
            switch response.result {
                case .success(let result):
                    promise(.success(result))
                case .failure(let error):
                    promise(.failure(error))
                }
            }
        }
        .eraseToAnyPublisher()
}

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.

struct ChatMessage {
    let id: String
    let content: String
    let dateCreated: Date
    let sender: MessageSender
}

enum MessageSender {
    case me
    case gpt
}

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).

import Combine

struct ContentView: View {
    @State var chatMessages: [ChatMessage] = []
    @State var messageText: String = ""

    let openAIService = OpenAIService()
    @State var cancellables = Set<AnyCancellable>()

    var body: some View {
        ...
    }
}

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.

func messageView(message: ChatMessage) -> some View {
    let senderIsMe = message.sender == .me
    return HStack {
        if senderIsMe { Spacer() }
            Text(message.content)
                .foregroundColor(senderIsMe ? .white : .black)
                .padding()
                .background(senderIsMe ? .blue : .gray.opacity(0.1))
                .cornerRadius(16)
        if !senderIsMe { Spacer() }
    }
}

Add the messageView to the body within the List.

struct ChatView: View {
    ...
    var body: some View {
        LazyVStack {
            List {
                ForEach(chatMessages, id: \.id) { message in
                    messageView(message: message)
                }
            }
        }
    }
}

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.

struct ContentView: View {
    ...

    func sendMessage() {
        let myMessage = ChatMessage(
            id: UUID().uuidString, 
            content: messageText, 
            dateCreated: Date(), 
            sender: .me
        )
        chatMessages.append(myMessage)

        openAIService.sendMessage(message: messageText)

        messageText = ""
    }
}

All that's left is to subscribe to the publisher in our sendMessage function, and add the message that's received to our array.

func sendMessage() {
    ...
    openAIService.sendMessage(message: messageText).sink { completion in
        // Handle error
    } receiveValue: { response in
        guard 
            let textResponse = response.choices.first?.text
                .trimmingCharacters(
                    in: .whitespacesAndNewlines
                        .union(.init(charactersIn: "\""))
                ) 
        else { return }
        let gptMessage = ChatMessage(
            id: response.id, 
            content: textResponse, 
            dateCreated: Date(), 
            sender: .gpt
        )
        chatMessages.append(gptMessage)
    }
    .store(in: &cancellables)
}

A Wrap

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! ✌️