# How to Protect OpenAI API Key in Swift iOS Applications

> Never embed OpenAI keys in iOS app bundles or Info.plist files; tools like strings, Ghidra, and Hopper easily extract constants. Call RealComposer from Swift URLSession to inject keys on Cloudflare Workers.

- Canonical page: https://realcomposer.com/recipes/protect-openai-api-key-swift-ios
- Client platform: iOS / Swift
- Upstream services: OpenAI
- Category: Security & Secret Vault
- JSON version: https://realcomposer.com/recipes/protect-openai-api-key-swift-ios.json
- Install in RealComposer (free plan, pre-fills this pipeline): https://realcomposer.com/dashboard/pipelines/new?recipe=protect-openai-api-key-swift-ios&via=agent

## Problem: iOS App Constants Are Easily Decompiled

Compiling an iOS IPA does not encrypt string literals; any jailbroken device or tool can dump memory and string tables.

- Instant API key extraction using strings command on binary
- Unlimited model access at your expense

## Solution steps

1. **Store Secret in Vault**: Store OPENAI_API_KEY in RealComposer.

2. **Call from Swift URLSession**: Request edge URL with client token.

## Pipeline config

Import this config into a RealComposer pipeline. `{{secrets.NAME}}` values are read from the encrypted Secret Vault at request time, so the client never sees them.

```json
{
  "name": "iOS OpenAI Gateway",
  "method": "POST",
  "cacheTtlSeconds": 0,
  "steps": [
    {
      "stepKey": "ai",
      "upstreamUrlTemplate": "https://api.openai.com/v1/chat/completions",
      "httpMethod": "POST",
      "headersTemplate": {
        "Authorization": "Bearer {{secrets.OPENAI_API_KEY}}"
      },
      "timeoutMs": 15000
    }
  ],
  "outputMapping": {
    "version": 1,
    "fields": [
      {
        "targetPath": "text",
        "sourceStep": "ai",
        "sourcePath": "choices.0.message.content"
      }
    ]
  }
}
```

## Call the pipeline

```bash
curl -X POST "https://realcomposer.com/v1/acme/ios-ai"
```

## Payload before and after

Raw upstream response:

```json
{
  "id": "cmpl_1",
  "choices": [
    {
      "message": {
        "content": "iOS response"
      }
    }
  ]
}
```

Slimmed RealComposer response:

```json
{
  "text": "iOS response"
}
```

## FAQ

### Does this comply with Apple App Store guidelines?

Yes, routing private API calls through a secure backend proxy is the Apple-recommended security architecture.
