This quickstart shows you how to get started with the Gemini API using the SDK of your choice.
Prerequisites
This quickstart assumes that you're familiar with using Xcode to develop Swift apps.
To complete this quickstart, make sure that your development environment and Swift app meet the following requirements:
- Xcode 15.0 or higher
- Your Swift app must target iOS 15 or higher, or macOS 12 or higher.
Install the Gemini API SDK
To use the Gemini API in your own Swift app, add the GoogleGenerativeAI
package to your app:
In Xcode, right-click on your project in the project navigator.
Select Add Packages from the context menu.
In the Add Packages dialog, paste the package URL in the search bar:
https://github.com/google/generative-ai-swift
Click Add Package. Xcode will now add the
GoogleGenerativeAI
package to your project.
Set up your API key
To use the Gemini API, you'll need an API key. If you don't already have one, create a key in Google AI Studio.
Get an API key from Google AI Studio
Then, configure your key.
It is strongly recommended that you do not check an API key into your
version control system. One alternative option is to store it in a
GenerativeAI-Info.plist
file, and then read the API key from the .plist
file. Make sure to put this .plist
file in the root folder of your app and
exclude it from version control.
enum APIKey {
// Fetch the API key from `GenerativeAI-Info.plist`
static var `default`: String {
guard let filePath = Bundle.main.path(forResource: "GenerativeAI-Info", ofType: "plist")
else {
fatalError("Couldn't find file 'GenerativeAI-Info.plist'.")
}
let plist = NSDictionary(contentsOfFile: filePath)
guard let value = plist?.object(forKey: "API_KEY") as? String else {
fatalError("Couldn't find key 'API_KEY' in 'GenerativeAI-Info.plist'.")
}
if value.starts(with: "_") {
fatalError(
"Follow the instructions at https://ai.google.dev/tutorials/setup to get an API key."
)
}
return value
}
}
Import the library
Import the GoogleAI
module:
import GoogleGenerativeAI
Make your first request
Use the
generateContent
method
to generate text.
let generativeModel =
GenerativeModel(
// Specify a Gemini model appropriate for your use case
name: "gemini-1.5-flash",
// Access your API key from your on-demand resource .plist file (see "Set up your API key"
// above)
apiKey: APIKey.default
)
let prompt = "Write a story about a magic backpack."
let response = try await generativeModel.generateContent(prompt)
if let text = response.text {
print(text)
}
What's next
Now that you're set up to make requests to the Gemini API, you can use the full range of Gemini API capabilities to build your apps and workflows. To get started with Gemini API capabilities, see the following guides:
For in-depth documentation of Gemini API methods and request parameters, see the guides in the API reference.