Building a GPT Client for iOS with SwiftUI
Adding AI-Generated Text to Your iOS App with SwiftUI and GPT #
This tutorial teaches you how to build a GPT client for iOS using SwiftUI. The tutorial covers how to send a request to the OpenAI GPT API and decode the JSON response to display the generated text.
Note that this tutorial will focus on the logic for sending and receiving requests to and from the OpenAI GPT API, and will not cover all the UI details involved in building the app.
For the full code, including the UI implementation, you can visit my Github repo containing working code samples for creating iOS and Android apps
What is GPT? #
GPT, or Generative Pre-trained Transformer, is a type of machine learning model that is capable of generating natural language text. It is a type of language model that has been pre-trained on large amounts of text data, and can be fine-tuned for specific tasks, such as generating text in response to a prompt.
What will we build? #
We will build an app that takes a user input from a TextField, sends it to the GPT API, receives the response, and decodes the JSON in order to display the answer as animated Text. The sendRequest
function is responsible for communicating with the OpenAI GPT API. After encoding the user’s question as a JSON payload, it sends a POST
request to the API. If the API responds with a status code of 200, the function extracts the generated text from the JSON response and displays it as animated text using SwiftUI’s Text
view. If the API responds with an error, the function displays an error message instead.
Here is an animated screenshot of the final app:
Sending a Request to the GPT API #
We will now show the code that is necessary to send a request to the GPT API. A step-by-step explanation will follow.
func sendRequest(question: String) async throws {
guard !question.isEmpty else { return }
let requestDto = RequestDto(prompt: question, max_tokens: 100, model: "text-davinci-003")
guard let payload = try? JSONEncoder().encode(requestDto) else { return }
let url = URL(string: "https://api.openai.com/v1/completions")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = payload
request.setValue("Bearer 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", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
isLoading = true
let (data, response) = try await URLSession.shared.data(for: request)
guard (response as? HTTPURLResponse)?.statusCode == 200 else{
DispatchQueue.main.async {
self.answer = "Unable to receive answer."
self.isLoading = false
}
return
}
let json = try? JSONSerialization.jsonObject(with: data, options: [])
if let json = json as? [String: Any],
let choices = json["choices"] as? [[String: Any]],
let firstChoice = choices.first,
let text = firstChoice["text"] as? String {
DispatchQueue.main.async {
self.answer = text.replacingOccurrences(of: "^\\s*", with: "", options: .regularExpression)
self.isLoading = false
}
}
}
The source code above allows the app to communicate with the OpenAI GPT API. Here is a brief explanation of the main parts of the code:
- The
async
keyword indicates that this function is asynchronous, meaning that it will run in the background and not block the main thread. - The
RequestDto
object is created with the user’s question, the maximum number of tokens to generate, and the GPT model to use. - The
payload
variable is created by encoding theRequestDto
object as JSON. - The
url
variable is set to the URL of the OpenAI GPT API. - The
request
variable is created with the URL and HTTP method set toPOST
. The payload is set as the HTTP body, and the authorization token and content type are set as HTTP header fields. - The
data
andresponse
variables are created by sending the HTTP request to the API usingsession.data(for: request)
. - The
guard
statement checks whether the API response has a status code of 200. If it does not, theanswer
variable is set to “Unable to receive answer” and theisLoading
variable is set tofalse
. - The
json
variable is created by deserializing the API response data usingJSONSerialization.jsonObject(with: data, options: [])
. - The generated text is extracted from the
json
variable and displayed in theanswer
variable.
Note: The Authorization
header in the code above contains an API key that is specific to the developer who created it, in this case me. If you plan to use this code, you will need to replace the API key with your own.
To obtain an API key for the OpenAI API, you will need to create an account on the OpenAI website (openai.com). Once you have an account, navigate to the API section of the website and follow the instructions to create an API key. Make sure to keep your API key secure and do not share it with others.
Conclusion #
In this tutorial, we build an iOS app that takes user input, sends it to the OpenAI GPT API, and displays the generated text as animated SwiftUI Text.
I hope you found this tutorial informative and that it has inspired you to create your project based on the GPT API. If you have any questions or feedback, feel free to leave a comment.
The full code can be downloaded from my repo that contains working code samples for creating iOS and Android apps: https://github.com/twissmueller/mobile-snippets
Thank you for reading!
- If you enjoyed this, please follow me on Medium.
- Buy me a coffee or send me a tip.
- Support me and other Medium writers by signing up here.