Code Examples

Take Screenshots with Swift

Ready-to-copy Swift code for capturing website screenshots, generating PDFs, and processing pages at scale. Uses URLSession (Foundation).

Quick Start

Screenshot in Swift — minimal example

The simplest way to capture a screenshot. Just a URL and your API key.

Swiftquickstart
var components = URLComponents(string: "https://api.screenshotdev.com/v1/screenshot")!
components.queryItems = [
    URLQueryItem(name: "url", value: "https://example.com"),
    URLQueryItem(name: "access_key", value: "YOUR_ACCESS_KEY"),
]
let (data, _) = try await URLSession.shared.data(from: components.url!)
try data.write(to: URL(fileURLWithPath: "screenshot.png"))
Full Example

Production-ready Swift script

Complete working script with options for viewport, format, full page capture, and error handling.

Swiftfull example
import Foundation

let apiKey = "YOUR_ACCESS_KEY"
let baseURL = "https://api.screenshotdev.com/v1/screenshot"

func takeScreenshot(
    url: String,
    format: String = "webp",
    width: Int = 1280,
    fullPage: Bool = false,
    darkMode: Bool = false
) async throws -> Data {
    var components = URLComponents(string: baseURL)!
    components.queryItems = [
        URLQueryItem(name: "url", value: url),
        URLQueryItem(name: "access_key", value: apiKey),
        URLQueryItem(name: "format", value: format),
        URLQueryItem(name: "width", value: String(width)),
        URLQueryItem(name: "full_page", value: String(fullPage)),
        URLQueryItem(name: "dark_mode", value: String(darkMode)),
    ]

    let (data, response) = try await URLSession.shared.data(from: components.url!)
    guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
        let body = String(data: data, encoding: .utf8) ?? ""
        throw URLError(.badServerResponse, userInfo: [NSLocalizedDescriptionKey: body])
    }
    return data
}

let img = try await takeScreenshot(url: "https://example.com", format: "webp", width: 1440, fullPage: true)
try img.write(to: URL(fileURLWithPath: "screenshot.webp"))
print("Saved screenshot.webp (\(img.count) bytes)")
Advanced

More Swift examples

PDF generation, batch processing, webhooks, CSS/JS injection, and S3 upload.

PDF Generation

Swiftpdf
var components = URLComponents(string: "https://api.screenshotdev.com/v1/pdf")!
components.queryItems = [
    URLQueryItem(name: "url", value: "https://example.com"),
    URLQueryItem(name: "access_key", value: "YOUR_ACCESS_KEY"),
    URLQueryItem(name: "format", value: "a4"),
    URLQueryItem(name: "landscape", value: "false"),
    URLQueryItem(name: "margin", value: "20px"),
]
let (data, _) = try await URLSession.shared.data(from: components.url!)
try data.write(to: URL(fileURLWithPath: "page.pdf"))

Batch Screenshots

Swiftbatch
let urls = [
    "https://example.com",
    "https://github.com",
    "https://news.ycombinator.com",
]

try await withThrowingTaskGroup(of: (String, Int).self) { group in
    for url in urls {
        group.addTask {
            let img = try await takeScreenshot(url: url, format: "webp")
            let host = URL(string: url)!.host!
            let filename = "\(host).webp"
            try img.write(to: URL(fileURLWithPath: filename))
            return (filename, img.count)
        }
    }
    for try await (name, size) in group {
        print("  \(name) (\(size) bytes)")
    }
}

Async with Webhooks

Swiftwebhooks
var request = URLRequest(url: URL(string: "https://api.screenshotdev.com/v1/screenshot")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONEncoder().encode([
    "url": "https://example.com",
    "access_key": "YOUR_ACCESS_KEY",
    "webhook_url": "https://your-app.com/api/webhooks/screenshot",
    "format": "webp",
])

let (data, _) = try await URLSession.shared.data(for: request)
let job = try JSONDecoder().decode([String: String].self, from: data)
print("Job queued: \(job["id"] ?? "")")

Custom CSS/JS Injection

Swiftinject
var components = URLComponents(string: baseURL)!
components.queryItems = [
    URLQueryItem(name: "url", value: "https://example.com"),
    URLQueryItem(name: "access_key", value: apiKey),
    URLQueryItem(name: "inject_css", value: "body { font-family: 'Inter', sans-serif; } .ad { display: none; }"),
    URLQueryItem(name: "inject_js", value: "document.querySelectorAll('[data-cookie-banner]').forEach(el => el.remove())"),
    URLQueryItem(name: "block_ads", value: "true"),
]
let (data, _) = try await URLSession.shared.data(from: components.url!)
try data.write(to: URL(fileURLWithPath: "clean.webp"))

S3 Upload

Swifts3
import AWSS3

// 1. Capture
let img = try await takeScreenshot(url: "https://example.com", format: "webp")

// 2. Upload
let s3 = try S3Client(region: "us-east-1")
_ = try await s3.putObject(input: PutObjectInput(
    body: .data(img),
    bucket: "my-screenshots",
    contentType: "image/webp",
    key: "captures/example-com.webp"
))

Try it live

Test the API in the interactive playground — pre-filled with Swift snippets.

Setup

Installation

Install the HTTP library used in the examples above.

Terminalinstall
# No dependencies — uses Foundation URLSession

Uses URLSession (Foundation). Any HTTP client that supports GET requests will work.

More Examples

Code examples in other languages

Start capturing screenshots
with Swift today.

100 free API calls per month. No credit card. First screenshot in under 30 seconds.

Take Screenshots with Swift — ScreenshotDEV