Offline AI on iOS: Using CoreML with SwiftUI
📱 Why Offline AI Matters in 2025
With increasing privacy concerns, patchy internet access, and user expectations for instant results, offline AI is becoming a must-have in iOS apps.
CoreML, Apple’s on-device machine learning framework, lets you run AI models directly on the device. That means:
- No network latency
- Full user privacy
- Instant predictions
- Better battery performance
- Works anywhere, anytime
Today, you’ll learn how to integrate CoreML with SwiftUI to build a powerful offline image classifier using a pre-trained ML model.
🎯 Use Case: Offline Image Classifier in SwiftUI
We’ll build an app that:
- Lets users select or take a photo
- Uses MobileNetV2 to classify the image
- Runs entirely offline
- Displays the AI prediction in a sleek SwiftUI UI
🔧 Step 1: Add CoreML Model to Xcode
- Download MobileNetV2.mlmodel from Apple’s Model Gallery.
- Drag and drop the file into your Xcode project.
- Xcode will automatically create a Swift class (
MobileNetV2.swift
) for easy integration.
⚙️ Step 2: CoreML Prediction Handler
Create a helper class to handle predictions from the model.
import CoreML
import Vision
import UIKit
class MLHandler {
static let shared = MLHandler()
private let model = try! VNCoreMLModel(for: MobileNetV2().model)
func classify(image: UIImage, completion: @escaping (String?) -> Void) {
let request = VNCoreMLRequest(model: model) { request, _ in
if let result = request.results?.first as? VNClassificationObservation {
completion(result.identifier)
} else {
completion("Unknown")
}
}
guard let ciImage = CIImage(image: image) else {
completion(nil)
return
}
let handler = VNImageRequestHandler(ciImage: ciImage)
try? handler.perform([request])
}
}
🧠 Step 3: ViewModel to Bridge SwiftUI
import SwiftUI
class ImageClassifierViewModel: ObservableObject {
@Published var image: UIImage?
@Published var prediction: String = "No prediction yet"
func classifyImage() {
guard let img = image else { return }
MLHandler.shared.classify(image: img) { [weak self] result in
DispatchQueue.main.async {
self?.prediction = result ?? "Error"
}
}
}
}
🎨 Step 4: Build SwiftUI Interface
struct ContentView: View {
@StateObject var viewModel = ImageClassifierViewModel()
@State private var showImagePicker = false
var body: some View {
VStack(spacing: 20) {
if let image = viewModel.image {
Image(uiImage: image)
.resizable()
.scaledToFit()
.frame(height: 300)
}
Text(viewModel.prediction)
.font(.headline)
.padding()
Button("Select Image") {
showImagePicker.toggle()
}
Button("Classify Image") {
viewModel.classifyImage()
}
.disabled(viewModel.image == nil)
}
.sheet(isPresented: $showImagePicker) {
ImagePicker(image: $viewModel.image)
}
.padding()
}
}
🖼 Image Picker: UIKit Integration in SwiftUI
import SwiftUI
import UIKit
struct ImagePicker: UIViewControllerRepresentable {
@Binding var image: UIImage?
func makeUIViewController(context: Context) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
let parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
parent.image = info[.originalImage] as? UIImage
picker.dismiss(animated: true)
}
}
}
💡 Why CoreML + SwiftUI Is the Perfect Combo
This integration gives your app:
- 💡 Offline Inference: No network needed
- 🔐 On-device Privacy: No personal data sent to cloud
- ⚡️ Real-time Predictions: Fast, smooth UX
- 🔋 Battery Optimization: CoreML is hardware-accelerated
- 🧩 SwiftUI Friendly: Fully native experience
📢 Final Thoughts
With just a few lines of Swift code, you’ve built an AI-powered iOS app that runs entirely offline — no internet, no servers, just pure machine learning magic.
This is the future of privacy-first, lightning-fast mobile AI. And you’re already building it.
Comments
Post a Comment