Step 3 — See you (the eyes follow your face)

Goal: your companion sees you through the front camera and its eyes follow your face as you move. When nobody is around, it goes back to looking around on its own. Everything runs on the phone — nothing is recorded or sent anywhere. :stopwatch: ~25 minutes. :white_check_mark: Tested on iPhone: builds in Xcode and the eyes follow your face.

Builds on Step 2 — Listen & speak.

1. Allow the camera

Your target → Info tab → add:

Key Value (example)
Privacy - Camera Usage Description Your companion uses the camera to see you and follow you with its eyes. Nothing is recorded or sent anywhere.

2. Add a new file: Sight.swift

import AVFoundation
import Vision

/// 📷 Sight: the front camera + Apple's Vision face detection.
/// `face` is where the closest face is, from -1 (left/top) to 1 (right/bottom), or nil when nobody is in view.
/// Thread safety: the camera state is only touched on `queue`, and `face` only on the main thread,
/// which is why it's safe to mark the class `@unchecked Sendable`.
final class Sight: NSObject, ObservableObject, AVCaptureVideoDataOutputSampleBufferDelegate, @unchecked Sendable {
    @Published var face: CGPoint?

    private let session = AVCaptureSession()
    private let queue = DispatchQueue(label: "companion.sight")
    private var configured = false
    private var frame = 0

    /// Asks for camera permission (once) and starts watching.
    func start() async {
        guard await AVCaptureDevice.requestAccess(for: .video) else { return }
        queue.async { [self] in
            if !configured { configure(); configured = true }
            if !session.isRunning { session.startRunning() }
        }
    }

    func stop() {
        queue.async { [self] in session.stopRunning() }
    }

    private func configure() {
        session.beginConfiguration()
        session.sessionPreset = .vga640x480
        if let camera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front),
           let input = try? AVCaptureDeviceInput(device: camera),
           session.canAddInput(input) {
            session.addInput(input)
        }
        let output = AVCaptureVideoDataOutput()
        output.alwaysDiscardsLateVideoFrames = true
        output.setSampleBufferDelegate(self, queue: queue)
        if session.canAddOutput(output) { session.addOutput(output) }
        session.commitConfiguration()
    }

    /// Called for every camera frame (on our background queue).
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        frame += 1
        guard frame % 3 == 0,                                   // ~10 checks per second is plenty
              let pixels = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }

        let request = VNDetectFaceRectanglesRequest()
        // Front camera, phone held upright: the image is rotated and mirrored like a selfie.
        let handler = VNImageRequestHandler(cvPixelBuffer: pixels, orientation: .leftMirrored)
        try? handler.perform([request])

        // Pick the biggest (closest) face. Vision boxes go from 0 to 1, with y measured from the bottom.
        let box = (request.results ?? []).max { $0.boundingBox.width < $1.boundingBox.width }?.boundingBox
        let point = box.map { CGPoint(x: ($0.midX - 0.5) * 2, y: (0.5 - $0.midY) * 2) }

        DispatchQueue.main.async { self.face = point }
    }
}

What’s inside:

  • AVCaptureSession streams the front camera (small 640×480 frames — plenty for faces, light on the battery).
  • VNDetectFaceRectanglesRequest (Apple Vision) finds faces in each frame — fully on-device.
  • We keep the biggest face (the closest person) and turn its position into a value from -1 to 1, so the UI doesn’t care about camera details.
  • Only every 3rd frame is checked (~10 times per second) to save battery.

3. Update ContentView.swift

import SwiftUI

struct ContentView: View {
    @StateObject private var ears = Ears()
    @StateObject private var voice = Voice()
    @StateObject private var sight = Sight()
    @State private var blinking = false
    @State private var look: CGSize = .zero
    @State private var lastReply = ""

    var body: some View {
        ZStack {
            Color.black.ignoresSafeArea()

            VStack(spacing: 40) {
                Spacer()
                HStack(spacing: 56) {
                    Eye(blinking: blinking, talking: voice.isSpeaking)
                    Eye(blinking: blinking, talking: voice.isSpeaking)
                }
                .offset(look)
                .scaleEffect(ears.isListening ? 1.12 : 1)          // eyes widen while listening
                .animation(.easeInOut(duration: 0.3), value: ears.isListening)

                Text(ears.isListening ? ears.transcript : lastReply)
                    .font(.title3)
                    .foregroundStyle(.white.opacity(0.8))
                    .multilineTextAlignment(.center)
                    .frame(minHeight: 60)
                    .padding(.horizontal)

                Spacer()

                Button(action: toggleListening) {
                    Image(systemName: ears.isListening ? "stop.circle.fill" : "mic.circle.fill")
                        .font(.system(size: 72))
                        .foregroundStyle(ears.isListening ? .red : Color(red: 0.16, green: 0.55, blue: 0.89))
                }
                .padding(.bottom, 30)

                if ears.permissionDenied {
                    Text("Allow Microphone and Speech Recognition in Settings.")
                        .font(.footnote).foregroundStyle(.orange)
                }
            }
        }
        .statusBarHidden()
        .task { await live() }
        .task { await sight.start() }
        .onDisappear { sight.stop() }
        .onChange(of: sight.face) { _, face in
            guard let face else { return }                         // nobody there: idle wandering takes over
            withAnimation(.easeOut(duration: 0.25)) {
                look = CGSize(width: face.x * 45, height: face.y * 30)   // look toward the person
            }
        }
    }

    /// Tap once to start listening, tap again to stop — then the companion answers.
    func toggleListening() {
        if ears.isListening {
            ears.stop()
            let heard = ears.transcript
            lastReply = Brain.reply(to: heard)
            voice.say(lastReply)
        } else {
            Task {
                guard await ears.requestPermissions() else { return }
                try? ears.start()
            }
        }
    }

    func blink() async {
        withAnimation(.easeIn(duration: 0.08)) { blinking = true }
        try? await Task.sleep(for: .milliseconds(110))
        withAnimation(.easeOut(duration: 0.14)) { blinking = false }
    }

    func live() async {
        while !Task.isCancelled {
            try? await Task.sleep(for: .seconds(Double.random(in: 2...5)))
            await blink()
            if Bool.random() && !ears.isListening && sight.face == nil {
                withAnimation(.spring(response: 0.6, dampingFraction: 0.7)) {
                    look = CGSize(width: .random(in: -40...40), height: .random(in: -20...20))
                }
            }
        }
    }
}

struct Eye: View {
    var blinking: Bool
    var talking: Bool
    @State private var bounce = false
    private let blue = Color(red: 0.16, green: 0.55, blue: 0.89)

    var body: some View {
        Ellipse()
            .fill(blue)
            .frame(width: 90, height: 130)
            .scaleEffect(x: 1, y: blinking ? 0.08 : (talking && bounce ? 0.85 : 1))
            .shadow(color: blue.opacity(0.8), radius: 24)
            .onChange(of: talking) { _, isTalking in
                withAnimation(isTalking ? .easeInOut(duration: 0.18).repeatForever() : .default) {
                    bounce = isTalking
                }
            }
    }
}

#Preview { ContentView() }

The new parts: a Sight object, .task { await sight.start() }, an .onChange(of: sight.face) that moves the eyes toward you, and idle wandering only when nobody is in view.

4. Run it on your iPhone

  1. Allow the camera the first time.
  2. Hold the phone upright and move your head left, right, up and down — the eyes follow you. :eyes:
  3. Cover the camera — after a moment the eyes go back to looking around by themselves.

Eyes going the wrong way? Cameras differ: in Sight.swift change .leftMirrored to .left (or flip the sign of face.x in ContentView).

How it works

  • The camera delivers frames on a background queue; Vision runs there too, so the UI stays smooth.
  • Results hop back to the main thread (DispatchQueue.main.async) before updating face, which SwiftUI watches.
  • The eye offset is just face × a few points — small movements look natural.

Privacy :locked:

Frames are analysed in memory and immediately discarded. Nothing is stored, recorded or uploaded. If you share your app, keep it that way — and tell users.

Make it yours :artist_palette:

Ask your AI assistant:

  • “Say ‘Hi there!’ when a face appears after nobody was around for 10 seconds.”
  • “Make the eyes bigger when the person comes closer (use the face box size).”
  • “Fall asleep (half-closed eyes) after 2 minutes with nobody in view, and wake up when someone appears.”
  • “Count how many faces are in view and show ‘Hello, everyone!’ when there are 2 or more.”

Share a video of the eyes following you in Show & Tell! :movie_camera:

:left_arrow: Step 2 — Listen & speak · :right_arrow: Next: Step 4 — Think

This is a wiki post — if something needs a fix for a newer Xcode or iOS, please update it.


:warning: Disclaimer: this code is shared by the community for learning, as is, without any warranty. We can’t guarantee that it compiles on your setup or works perfectly — Xcode, iOS and AI provider APIs change often. Use it at your own risk and never share your API keys. Found a problem? Reply below and help us fix it. :blue_heart: