To integrate your OpenAI API key into an Xcode app securely: Do not hardcode it. Instead, create a Config.xcconfig file, store the key as API_KEY = sk-your-key, and add it to your Info.plist. Then, access it in your Swift code using Bundle.main.object(forInfoDictionaryKey: "API_KEY"). This prevents your key from leaking into public repositories.

Why You Shouldn’t Hardcode API Keys
When building AI apps in Xcode, the biggest mistake beginners make is pasting the string sk-... directly into ViewController.swift.
- Security Risk: If you push to GitHub, bots will steal your key in seconds.
- Management: It makes it hard to swap keys for different environments (Debug vs. Release).
Step-by-Step Integration Guide
Step 1: Get Your API Key
- Log in to the OpenAI Platform.
- Go to API Keys and generate a new secret key. Copy it immediately.
Step 2: Create a Config File
- In Xcode, right-click your project folder -> New File.
- Search for Configuration Settings File, name it
Config.xcconfig. - Add this line inside:
OPENAI_API_KEY = sk-your-actual-api-key-here
Step 3: Link to Info.plist
- Go to your Project Settings (click the blue icon at the top left).
- Select your Target -> Build Settings.
- Search for “Info.plist Preprocessor Prefix File” (optional, but recommended for complex apps) or simply reference the variable in
Info.plist. - Open
Info.plist, right-click -> Add Row. - Key:
OpenAIKey, Value:$(OPENAI_API_KEY).
Step 4: Call It in Swift
Now you can safely use the key in your API service class:
Swift
var apiKey: String {
return Bundle.main.object(forInfoDictionaryKey: "OpenAIKey") as? String ?? ""
}
// Use apiKey in your HTTP headers