hyperproxy
Start free

Documentation / Swift · Gemini

Connect Gemini to your Swift app

This recipe connects Gemini through a HyperProxy gateway using the published Swift SDK 0.5.0. You need Swift 6.2, iOS 15 or later, a provider account with API access and a HyperProxy service. Provider usage is billed separately. Start with a non-streaming request, then add device security before shipping.

Updated · HyperProxy team

Call Gemini with a gateway app key

Add the HyperProxyGemini package product from HyperProxySwift 0.5.0 to your target. Use Swift 6.2 and iOS 15 or later. In Project → Services, select Gemini, paste the Google API credential there and create an app key. Copy this service's gateway URL. The complete Google key stays out of your app.

Pass a bare model ID enabled in your account. The SDK adds v1beta/models/ and :generateContent; do not add models/ to the argument.

Gemini.swift · SDK 0.5.0
import Foundation
import HyperProxyGemini

// HyperProxySwift 0.5.0; model is a bare ID available in your Google account.
func requestGemini(
  gatewayURL: URL, appKey: String, model: String, prompt: String,
  session: URLSession = .shared
) async throws -> HyperProxyJSONValue {
  let service = HyperProxy.gemini(
    gatewayURL: gatewayURL, appKey: appKey, session: session
  )
  let body: HyperProxyJSONValue = [
    "contents": [["role": "user", "parts": [["text": .string(prompt)]]]],
    "generationConfig": ["maxOutputTokens": 256]
  ]
  return try await service.modelsGenerateContent
    .path("model", model)
    .json(body)
    .jsonValue()
}

// Display a useful error without exposing response bodies or credentials.
func geminiErrorMessage(_ error: Error) -> String {
  if case HyperProxyError.httpStatus(let code, _, _) = error {
    switch code {
    case 401, 403: return "Check the service app key, device proof and provider access."
    case 429: return "Check quota and rate limits before retrying."
    default: return "AI request failed (HTTP \(code))."
    }
  }
  return "Check your connection and try again."
}

Call requestGemini(gatewayURL:appKey:model:prompt:) from an async task. Read text from candidates[].content.parts[].text; a blocked response can omit candidates, so show an empty-result state. Update SwiftUI state on the main actor. Pass caught errors to geminiErrorMessage, and cancel the task when the view closes.

The provider's usageMetadata supplies token counts. HyperProxy extracts usage on the server; prompt, cached and thinking tokens have distinct pricing rules. Inspect cost coverage in Overview. Missing metadata or an unknown price does not establish zero cost.

This example is non-streaming. To add streaming, use the provider's stream endpoint and consume terminal usage; do not treat an early text fragment as a completed request.

Protocol reference: Google GenerateContent API. Validation on 8 October 2026: the exact code compiled and ran against the 0.5.0 tag with controlled responses. Checks cover the native route, app-key header, JSON body, decoded usage and HTTP 429. This is a client contract check; run a real request with your provider account to verify model availability, device policy and billing.

Verify it works

Run one request with your own service gateway URL, app key and an available Gemini model. Confirm the response, then open Project → Requests and find its HTTP status and request ID. In Overview, verify the model, token counts and cost coverage. Use Setup → Check recorded data to confirm the connection.

Troubleshooting

401 or 403

Verify that the app key belongs to this service, has not expired and meets the configured device proof requirements. Check provider entitlement separately; inspect the dashboard error code before rotating keys.

429 or exhausted quota

Inspect whether the limit is from HyperProxy or the provider. Check account quota, service limits and provider usage. Honor Retry-After when present and use bounded backoff; do not loop automatically.

Empty text or unknown cost

Inspect the provider response shape and content policy result. Missing text may be a valid tool or safety response. Missing prices or usage must stay unknown; do not report a free request.

Full error-code reference

Next steps

1,000 requests per month shared across projects. No card required. Provider charges are separate.