Integrating Firebase with SwiftUI and LLM (GPT) Responses: Build Smart iOS Apps

 

Learn how to combine Firebase and GPT-based AI in SwiftUI to create intelligent, data-driven iOS apps that feel like magic. πŸš€

✨ Why This Matters

As iOS developers in 2025, we’re not just building apps — we’re crafting smart experiences.

With the rise of LLMs like OpenAI’s GPT and tools like Firebase, combining SwiftUI + GPT + Firebase gives your app:

  • πŸ’¬ AI-powered content generation
  • πŸ”„ Real-time sync across devices
  • ☁️ Scalable backend with zero server management
  • 🧠 Personalized experiences for every user

Today, we’ll build a simple yet powerful iOS app using these three superpowers.

🧠 What You’ll Learn

  • How to set up Firebase in a SwiftUI app
  • How to connect to GPT (OpenAI API) from Swift
  • How to store & retrieve GPT responses using Firestore
  • Best practices for data handling, security, and latency
  • A beautiful SwiftUI interface to tie it all together

πŸš€ Use Case: AI-Powered Daily Affirmations App

We’ll build a Daily Affirmation App that:

  1. Uses GPT to generate daily affirmations
  2. Saves the result in Firebase Firestore
  3. Syncs affirmations across devices
  4. Displays them in a modern SwiftUI interface

Let’s get started πŸ‘‡

πŸ›  Step 1: Setup Firebase in Your SwiftUI Project

πŸ”— 1.1 Create Firebase Project

  • Go to Firebase Console
  • Create a new project → Add iOS app
  • Register your app with the correct Bundle ID
  • Download GoogleService-Info.plist and add it to Xcode

πŸ“¦ 1.2 Add Firebase SDK

Add Firebase via Swift Package Manager:

.package(url: "https://github.com/firebase/firebase-ios-sdk.git", from: "10.0.0")

⚙️ 1.3 Initialize Firebase in App

import FirebaseCore

@main
struct AIApp: App {
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}

πŸ€– Step 2: Connect GPT (OpenAI API)

Create a network layer for GPT interaction:

struct GPTService {
let apiKey = "<YOUR_OPENAI_API_KEY>"

func fetchAffirmation(completion: @escaping (String) -> Void) {
let url = URL(string: "https://api.openai.com/v1/chat/completions")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: Any] = [
"model": "gpt-3.5-turbo",
"messages": [["role": "user", "content": "Give me a positive daily affirmation."]],
"temperature": 0.8
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
URLSession.shared.dataTask(with: request) { data, _, _ in
guard let data = data,
let response = try? JSONDecoder().decode(GPTResponse.self, from: data) else { return }
DispatchQueue.main.async {
completion(response.choices.first?.message.content ?? "You're amazing!")
}
}.resume()
}
}
struct GPTResponse: Codable {
struct Choice: Codable {
struct Message: Codable {
let content: String
}
let message: Message
}
let choices: [Choice]
}

πŸ”₯ Step 3: Save and Retrieve GPT Output from Firebase Firestore

πŸ“„ Model + ViewModel

import FirebaseFirestore
import FirebaseFirestoreSwift

struct Affirmation: Codable, Identifiable {
let id: String
let text: String
let date: Date
}
class AffirmationViewModel: ObservableObject {
@Published var affirmations: [Affirmation] = []
private let db = Firestore.firestore()
func saveAffirmation(_ text: String) {
let id = UUID().uuidString
let affirmation = Affirmation(id: id, text: text, date: Date())
try? db.collection("affirmations").document(id).setData(from: affirmation)
}
func fetchAffirmations() {
db.collection("affirmations").order(by: "date", descending: true)
.addSnapshotListener { snapshot, _ in
self.affirmations = snapshot?.documents.compactMap {
try? $0.data(as: Affirmation.self)
} ?? []
}
}
}

🎨 Step 4: Build the SwiftUI Interface

struct ContentView: View {
@StateObject var viewModel = AffirmationViewModel()
let gptService = GPTService()

var body: some View {
NavigationView {
List(viewModel.affirmations) { affirmation in
Text(affirmation.text)
.font(.title3)
.padding()
}
.navigationTitle("🌞 Daily Affirmations")
.toolbar {
Button("New") {
gptService.fetchAffirmation { text in
viewModel.saveAffirmation(text)
}
}
}
.onAppear {
viewModel.fetchAffirmations()
}
}
}
}

πŸ’‘ Pro Tips for Production-Ready AI Apps

✅ Hide Your API Keys
Use a backend proxy or secure vaults like Firebase Functions or AWS Secrets Manager.

πŸ“Ά Add Loading & Error States
Improve UX with @State isLoading and alerts for failed requests.

🧠 Local Caching
Use Realm or CoreData for offline support.

πŸ”’ Firebase Auth Integration
Add user-level data storage and personalization.

πŸ“’ Final Thoughts

And just like that — you’ve built an intelligent, cloud-connected, GPT-powered iOS app using SwiftUI + Firebase + OpenAI.

This is the future of mobile development — and you’re building it now.


Comments

Popular posts from this blog

Dependency Injection in iOS with SwiftUI

Using Core ML with SwiftUI: Build an AI-Powered App

CI/CD for iOS Projects with Xcode: A Complete Guide