iOS Development
Screenshot Automation
iOS Programming
Swift
iOS Coding Techniques

How to take a screenshot programmatically on iOS

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Programmatic screenshots on iOS are useful for bug reports, share cards, visual regression checks, and support workflows. The safest approach is rendering the specific view you need, instead of trying to capture system UI globally. This guide covers modern UIKit screenshot techniques, saving output, and handling sensitive content.

Capture a UIView Using UIGraphicsImageRenderer

For most apps, capturing a target view is enough.

swift
1import UIKit
2
3func snapshot(of view: UIView) -> UIImage {
4    let format = UIGraphicsImageRendererFormat()
5    format.scale = UIScreen.main.scale
6    format.opaque = view.isOpaque
7
8    let renderer = UIGraphicsImageRenderer(bounds: view.bounds, format: format)
9    return renderer.image { _ in
10        view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
11    }
12}

UIGraphicsImageRenderer is preferred over older APIs because it is safer and memory-friendly.

Capture the Key Window Content

If you need the full visible app interface, snapshot the active key window.

swift
1import UIKit
2
3func keyWindowImage() -> UIImage? {
4    guard let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
5          let window = scene.windows.first(where: { $0.isKeyWindow }) else {
6        return nil
7    }
8
9    let renderer = UIGraphicsImageRenderer(bounds: window.bounds)
10    let image = renderer.image { _ in
11        window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
12    }
13    return image
14}

This captures what your app renders, not protected system overlays.

Save Screenshot to Photos

If users need a saved image, write it to the photo library with proper permissions.

swift
1import Photos
2import UIKit
3
4func saveToPhotos(_ image: UIImage, completion: @escaping (Bool, Error?) -> Void) {
5    PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in
6        guard status == .authorized || status == .limited else {
7            completion(false, nil)
8            return
9        }
10
11        PHPhotoLibrary.shared().performChanges({
12            PHAssetChangeRequest.creationRequestForAsset(from: image)
13        }, completionHandler: completion)
14    }
15}

Add the correct photo library usage description key in your app configuration.

Share Screenshot In-App

Often the image should be shared immediately instead of saved.

swift
1import UIKit
2
3func presentShareSheet(image: UIImage, from controller: UIViewController) {
4    let activity = UIActivityViewController(activityItems: [image], applicationActivities: nil)
5    controller.present(activity, animated: true)
6}

This is useful for support tickets and quick user feedback workflows.

Protect Sensitive Data

Screenshots may include personal or confidential data. Before capturing, consider temporarily masking sensitive labels or account values.

If screenshots are uploaded to servers, encrypt transport and define retention policies. Treat screenshots like user data, not harmless images.

For internal debugging features, gate screenshot tools behind debug menus or role checks.

Capture Specific Subviews for Reporting

Many workflows only need a component snapshot, such as a chart or error panel. Capturing smaller regions reduces memory usage and avoids accidental inclusion of private data.

swift
1import UIKit
2
3func snapshotSubview(_ view: UIView, in container: UIView) -> UIImage? {
4    let targetFrame = container.convert(view.bounds, from: view)
5    guard targetFrame.width > 0, targetFrame.height > 0 else { return nil }
6
7    let renderer = UIGraphicsImageRenderer(bounds: targetFrame)
8    return renderer.image { _ in
9        container.drawHierarchy(in: container.bounds, afterScreenUpdates: true)
10    }
11}

For deterministic visual tests, set fixed interface style, content size category, and locale before capture. Stable rendering inputs make image diffs reliable in CI and reduce flaky screenshot assertions.

Common Pitfalls

A common issue is capturing too early before layout updates complete. Ensure views are fully rendered, or call after animation and layout settle.

Another pitfall is assuming programmatic capture includes system elements such as control center. App-level rendering can only capture your own interface.

Developers also forget photo permission handling and see silent save failures.

A final issue is large image memory pressure on older devices. Resize or compress images before network upload.

Summary

  • Use UIGraphicsImageRenderer for modern, reliable view snapshots.
  • Capture key window when full visible app screen is needed.
  • Save to photos only with proper authorization handling.
  • Share images directly for support and feedback flows.
  • Mask sensitive content and manage screenshot data securely.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.