8.2 C
Canberra
Wednesday, October 22, 2025

Integrating Google Gemini AI with Swift and SwiftUI


On the upcoming WWDC, Apple is anticipated to announce an on-device massive language mannequin (LLM). The following model of the iOS SDK will seemingly make it simpler for builders to combine AI options into their apps. Whereas we await Apple’s debut of its personal Generative AI fashions, firms like OpenAI and Google already present SDKs for iOS builders to include AI options into cell apps. On this tutorial, we are going to discover Google Gemini, previously referred to as Bard, and show methods to use its API to construct a easy SwiftUI app.

We’re set to construct a Q&A app that makes use of the Gemini API. The app contains a simple UI with a textual content area for customers to enter their questions. Behind the scenes, we are going to ship the consumer’s query to Google Gemini to retrieve the reply.

swiftui-gemini-app-demo

Please be aware that it’s a must to use Xcode 15 (or up) to observe this tutorial.

Getting Began with Google Gemini APIs

Assuming that you simply haven’t labored with Gemini, the very very first thing is to go as much as get an API key for utilizing the Gemini APIs. To create one, you possibly can go as much as Google AI Studio and click on the Create API key button.

swiftui-google-gemini-api-key

Utilizing Gemini APIs in Swift Apps

It is best to now have created the API key. We’ll use this in our Xcode challenge. Open Xcode and create a brand new SwiftUI challenge, which I’ll name GeminiDemo. To retailer the API key, create a property file named GeneratedAI-Information.plist. On this file, create a key named API_KEY and enter your API key as the worth.

swiftui-gemini-property-list

To learn the API key from the property file, create one other Swift file named APIKey.swift. Add the next code to this file:

enum APIKey {
  // Fetch the API key from `GenerativeAI-Information.plist`
  static var `default`: String {

    guard let filePath = Bundle.important.path(forResource: "GenerativeAI-Information", ofType: "plist")
    else {
      fatalError("Could not discover file 'GenerativeAI-Information.plist'.")
    }

    let plist = NSDictionary(contentsOfFile: filePath)

    guard let worth = plist?.object(forKey: "API_KEY") as? String else {
      fatalError("Could not discover key 'API_KEY' in 'GenerativeAI-Information.plist'.")
    }

    if worth.begins(with: "_") {
      fatalError(
        "Observe the directions at https://ai.google.dev/tutorials/setup to get an API key."
      )
    }

    return worth
  }
}

For those who determine to make use of a distinct title for the property file as a substitute of the unique ā€˜GenerativeAI-Information.plist’, you will have to switch the code in your ā€˜APIKey.swift’ file. This modification is critical as a result of the code references the precise filename when fetching the API key. So, any change within the property file title needs to be mirrored within the code to make sure the profitable retrieval of the API key.

Including the SDK Utilizing Swift Bundle

The Google Gemini SDK is well accessible as a Swift Bundle, making it easy so as to add to your Xcode challenge. To do that, right-click the challenge folder within the challenge navigator and choose Add Bundle Dependencies. Within the dialog, enter the next package deal URL:

https://github.com/google/generative-ai-swift

You may then click on on the Add Bundle button to obtain and incorporate theĀ GoogleGenerativeAIĀ package deal into the challenge.

Constructing the App UI

Let’s begin with the UI. It’s simple, with solely a textual content area for consumer enter and a label to show responses from Google Gemini.

Open ContentView.swift and declare the next properties:

@State non-public var textInput = ""
@State non-public var response: LocalizedStringKey = "Howdy! How can I allow you to right now?"

@State non-public var isThinking = false

The textInput variable is used to seize consumer enter from the textual content area. The response variable shows the API’s returned response. Given the API’s response time, we embrace an isThinking variable to observe the standing and present animated results.

For the physique variable, substitute it with the next code to create the consumer interface:

VStack(alignment: .main) {

    ScrollView {
        VStack {
            Textual content(response)
                .font(.system(.title, design: .rounded, weight: .medium))
                .opacity(isThinking ? 0.2 : 1.0)
        }
    }
    .contentMargins(.horizontal, 15, for: .scrollContent)

    Spacer()

    HStack {

        TextField("Kind your message right here", textual content: $textInput)
            .textFieldStyle(.plain)
            .padding()
            .background(Coloration(.systemGray6))
            .clipShape(RoundedRectangle(cornerRadius: 20))

    }
    .padding(.horizontal)
}

The code is sort of simple, particularly you probably have some expertise with SwiftUI. After making the adjustments, you need to see the next consumer interface within the preview.

swiftui-gemini-app-ui

Integrating with Google Gemini

Earlier than you should utilize the Google Gemini APIs, you first have to import the GoogleGenerativeAI module:

import GoogleGenerativeAI

Subsequent, declare a mannequin variable and initialize the Generative mannequin like this:

let mannequin = GenerativeModel(title: "gemini-pro", apiKey: APIKey.default)

Right here, we make the most of the gemini-pro mannequin, which is particularly designed to generate textual content from textual content enter.

To ship the textual content to Google Gemini, let’s create a brand new perform referred to as sendMessage():

func sendMessage() {
    response = "Pondering..."

    withAnimation(.easeInOut(period: 0.6).repeatForever(autoreverses: true)) {
        isThinking.toggle()
    }

    Activity {
        do {
            let generatedResponse = strive await mannequin.generateContent(textInput)

            guard let textual content = generatedResponse.textual content else  {
                textInput = "Sorry, Gemini received some issues.nPlease strive once more later."
                return
            }

            textInput = ""
            response = LocalizedStringKey(textual content)

            isThinking.toggle()
        } catch {
            response = "One thing went fallacious!n(error.localizedDescription)"
        }
    }
}

As you possibly can see from the code above, you solely have to name the generateContent methodology of the mannequin to enter textual content and obtain the generated response. The result’s in Markdown format, so we use LocalizedStringKey to wrap the returned textual content.

To name the sendMessage() perform, replace the TextField view and fasten the onSubmit modifier to it:

TextField("Kind your message right here", textual content: $textInput)
    .textFieldStyle(.plain)
    .padding()
    .background(Coloration(.systemGray6))
    .clipShape(RoundedRectangle(cornerRadius: 20))
    .onSubmit {
        sendMessage()
    }

On this state of affairs, when the consumer finishes inputting the textual content and presses the return key, the sendMessage() perform is known as to submit the textual content to Google Gemini.

That’s it! Now you can run the app in a simulator or execute it instantly within the preview to check the AI characteristic.

swiftui-generative-ai-demo

Abstract

This tutorial exhibits methods to combine Google Gemini AI right into a SwiftUI app. It solely requires just a few strains of code to allow your app with Generative AI options. On this demo, we use the gemini-pro mannequin to generate textual content from text-only enter.

Nonetheless, the capabilities of Gemini AI usually are not simply restricted to text-based enter. Gemini additionally affords a multimodal mannequin named gemini-pro-vision that enables builders to enter each textual content and pictures. We encourage you to take full benefit of this tutorial by modifying the supplied code and experimenting with it.

In case you have any questions concerning the tutorial, please let me know by leaving a remark beneath.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles