Communitygithub.com

JordanCoin/ios-skills-collection

PDF-Dokumente mit PDFKit anzeigen und bearbeiten. Nutzen Sie diese Fähigkeit, um mit PDFView PDF-Dateien darzustellen, PDFDocument-Instanzen zu erstellen oder zu ändern, Anmerkungen (Hervorhebungen, Notizen, Signaturen) hinzuzufügen, Text mit PDFSelection zu extrahieren, Seiten zu navigieren, Vorschaubilder zu generieren, PDF-Formulare auszufüllen oder PDFView in SwiftUI einzubetten.

Was ist ios-skills-collection?

Diese Fähigkeit bietet eine umfassende Anleitung zur Nutzung des PDFKit-Frameworks in iOS-Apps (Swift 6.3 / iOS 26+). Sie deckt alle wesentlichen Aspekte der PDF-Verarbeitung ab: das Anzeigen von Dokumenten mit PDFView (inklusive verschiedener Anzeigemodi wie Einzelseite, fortlaufend oder Doppelseite), das Laden von passwortgeschützten PDFs, die Seiten-Navigation mit Verlaufsverfolgung, die Textsuche (synchron und asynchron) sowie die Extraktion von Text aus bestimmten Bereichen. Ein besonderer Schwerpunkt liegt auf der Arbeit mit Annotationen – Hervorhebungen, Notizen, Freitext, Links und Formularelemente – inklusive einer Referenztabelle aller unterstützten Subtypen. Darüber hinaus wird die Einbindung von PDFView in SwiftUI über UIViewRepresentable beschrieben (mit korrektem Identitätsvergleich in updateUIView), ebenso wie die Verwendung von PDFThumbnailView für Vorschaubilder, Page-Overlays ab iOS 16 und die Behandlung häufiger Fehler (z.B. Thread-Sicherheit, Koordinatensystem-Unterschiede zwischen PDF und UIKit).

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/JordanCoin/ios-skills-collection/tree/HEAD/skills/dpearson2699--pdfkit

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

PDFKit

Zeigen Sie PDF-Dokumente an, navigieren Sie darin, durchsuchen, kommentieren und bearbeiten Sie sie mit PDFView, PDFDocument, PDFPage, PDFAnnotation und PDFSelection. Ziel: Swift 6.3 / iOS 26+.

Inhalt

Einrichtung

PDFKit benötigt keine Berechtigungen oder Einträge in der Info.plist.

import PDFKit

Verfügbarkeit: iOS 11+, iPadOS 11+, Mac Catalyst 13.1+, macOS 10.4+, tvOS 11+, visionOS 1.0+.

PDFs anzeigen

PDFView ist eine UIView-Unterklasse, die PDF-Inhalte rendert und Zoom, Scrollen, Textauswahl und Seitennavigation standardmäßig unterstützt.

import PDFKit
import UIKit

class PDFViewController: UIViewController {
    let pdfView = PDFView()

    override func viewDidLoad() {
        super.viewDidLoad()
        pdfView.frame = view.bounds
        pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.addSubview(pdfView)

        pdfView.autoScales = true
        pdfView.displayMode = .singlePageContinuous
        pdfView.displayDirection = .vertical

        if let url = Bundle.main.url(forResource: "sample", withExtension: "pdf") {
            pdfView.document = PDFDocument(url: url)
        }
    }
}

Anzeigemodi

ModusVerhalten
.singlePageEine Seite nach der anderen
.singlePageContinuousSeiten vertikal gestapelt, scrollbar
.twoUpZwei Seiten nebeneinander
.twoUpContinuousZwei Seiten mit fortlaufendem Scrollen

Skalierung und Darstellung

pdfView.autoScales = true
pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit
pdfView.maxScaleFactor = 4.0

pdfView.displaysPageBreaks = true
pdfView.pageShadowsEnabled = true
pdfView.interpolationQuality = .high

Dokumente laden

PDFDocument wird von einer URL, aus Data oder als leeres Dokument erstellt.

let fileDoc = PDFDocument(url: fileURL)
let dataDoc = PDFDocument(data: pdfData)
let emptyDoc = PDFDocument()

Passwortgeschützte PDFs

guard let document = PDFDocument(url: url) else { return }
if document.isLocked {
    if !document.unlock(withPassword: userPassword) {
        // Passwortabfrage anzeigen
    }
}

Speichern und Seitenbearbeitung

document.write(to: outputURL)
document.write(to: outputURL, withOptions: [
    .ownerPasswordOption: "ownerPass", .userPasswordOption: "userPass"
])
let data = document.dataRepresentation()

// Seiten (0-basiert)
let count = document.pageCount
document.insert(PDFPage(), at: count)
document.removePage(at: 2)
document.exchangePage(at: 0, withPageAt: 3)

Seitennavigation

PDFView bietet eine integrierte Navigation mit Verlaufsverfolgung.

// Zu einer bestimmten Seite springen
if let page = pdfView.document?.page(at: 5) {
    pdfView.go(to: page)
}

// Sequentielle Navigation
pdfView.goToNextPage(nil)
pdfView.goToPreviousPage(nil)
pdfView.goToFirstPage(nil)
pdfView.goToLastPage(nil)

// Navigationsstatus prüfen
if pdfView.canGoToNextPage { /* ... */ }

// Verlaufsnavigation
if pdfView.canGoBack { pdfView.goBack(nil) }

// Zu einem bestimmten Punkt auf einer Seite springen
let destination = PDFDestination(page: page, at: CGPoint(x: 0, y: 500))
pdfView.go(to: destination)

Seitenwechsel beobachten

NotificationCenter.default.addObserver(
    self, selector: #selector(pageChanged),
    name: .PDFViewPageChanged, object: pdfView
)

@objc func pageChanged(_ notification: Notification) {
    guard let page = pdfView.currentPage,
          let doc = pdfView.document else { return }
    let index = doc.index(for: page)
    pageLabel.text = "Seite \(index + 1) von \(doc.pageCount)"
}

Textsuche und -auswahl

Synchrone Suche

let results: [PDFSelection] = document.findString(
    "Suchbegriff", withOptions: [.caseInsensitive]
)

Asynchrone Suche

Verwenden Sie PDFDocumentDelegate für Hintergrundsuchen in großen Dokumenten. Implementieren Sie didMatchString(_:), um jedes Ergebnis zu erhalten, und documentDidEndDocumentFind(_:) für den Abschluss.

Inkrementelle Suche und Find-Interaktion

// Nächsten Treffer ab aktueller Auswahl finden
let next = document.findString("Begriff", fromSelection: current, withOptions: [.caseInsensitive])

// System-Suchleiste (iOS 16+)
pdfView.isFindInteractionEnabled = true

Textextraktion

let fullText = document.string                          // Gesamtes Dokument
let pageText = document.page(at: 0)?.string             // Einzelne Seite
let attributed = document.page(at: 0)?.attributedString  // Mit Formatierung

// Bereichsbasierte Extraktion
if let page = document.page(at: 0) {
    let selection = page.selection(for: CGRect(x: 50, y: 50, width: 400, height: 200))
    let text = selection?.string
}

Suchergebnisse hervorheben

let results = document.findString("wichtig", withOptions: [.caseInsensitive])
for selection in results { selection.color = .yellow }
pdfView.highlightedSelections = results

if let first = results.first {
    pdfView.setCurrentSelection(first, animate: true)
    pdfView.go(to: first)
}

Annotationen

Annotationen werden mit PDFAnnotation(bounds:forType:withProperties:) erstellt und zu einer PDFPage hinzugefügt.

Hervorhebungsannotation

func addHighlight(to page: PDFPage, selection: PDFSelection) {
    let highlight = PDFAnnotation(
        bounds: selection.bounds(for: page),
        forType: .highlight, withProperties: nil
    )
    highlight.color = UIColor.yellow.withAlphaComponent(0.5)
    page.addAnnotation(highlight)
}

Textnotiz-Annotation

let note = PDFAnnotation(
    bounds: CGRect(x: 100, y: 700, width: 30, height: 30),
    forType: .text, withProperties: nil
)
note.contents = "Dies ist ein Haftnotiz."
note.color = .systemYellow
note.iconType = .comment
page.addAnnotation(note)

Freitext-Annotation

let freeText = PDFAnnotation(
    bounds: CGRect(x: 50, y: 600, width: 300, height: 40),
    forType: .freeText, withProperties: nil
)
freeText.contents = "Hinzugefügter Kommentar"
freeText.font = UIFont.systemFont(ofSize: 14)
freeText.fontColor = .darkGray
page.addAnnotation(freeText)

Link-Annotation

let link = PDFAnnotation(
    bounds: CGRect(x: 50, y: 500, width: 200, height: 20),
    forType: .link, withProperties: nil
)
link.url = URL(string: "https://example.com")
page.addAnnotation(link)

// Interner Seitenlink
link.destination = PDFDestination(page: targetPage, at: .zero)

Annotationen entfernen

for annotation in page.annotations {
    page.removeAnnotation(annotation)
}

Referenztabelle der Annotationstypen

SubtypKonstanteZweck
Highlight.highlightTextmarkierung (gelbe Hervorhebung)
Underline.underlineTextmarkierung (Unterstreichung)
StrikeOut.strikeOutTextmarkierung (Durchstreichung)
Text.textHaftnotiz-Symbol
FreeText.freeTextInline-Textblock
Ink.inkFreihandzeichnungspfade
Link.linkURL oder Seitenziel
Line.lineGerade Linie mit Endpunkten
Square.squareRechteckform
Circle.circleEllipsenform
Stamp.stampStempel (Genehmigt, usw.)
Widget.widgetFormularelement (Textfeld, Kontrollkästchen)

Vorschaubilder

PDFThumbnailView

PDFThumbnailView zeigt einen Streifen mit Seitenminiaturen an, der mit einem PDFView verknüpft ist.

let thumbnailView = PDFThumbnailView()
thumbnailView.pdfView = pdfView
thumbnailView.thumbnailSize = CGSize(width: 60, height: 80)
thumbnailView.layoutMode = .vertical
thumbnailView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(thumbnailView)

Vorschaubilder programmatisch generieren

let thumbnail = page.thumbnail(of: CGSize(width: 120, height: 160), for: .mediaBox)

// Alle Seiten
let thumbnails = (0..<document.pageCount).compactMap {
    document.page(at: $0)?.thumbnail(of: CGSize(width: 120, height: 160), for: .mediaBox)
}

SwiftUI-Integration

Wickeln Sie PDFView in ein UIViewRepresentable für SwiftUI.

import SwiftUI
import PDFKit

struct PDFKitView: UIViewRepresentable {
    let document: PDFDocument

    func makeUIView(context: Context) -> PDFView {
        let pdfView = PDFView()
        pdfView.autoScales = true
        pdfView.displayMode = .singlePageContinuous
        pdfView.document = document
        return pdfView
    }

    func updateUIView(_ pdfView: PDFView, context: Context) {
        if pdfView.document !== document {
            pdfView.document = document
        }
    }
}

Verwendung

struct DocumentScreen: View {
    let url: URL

    var body: some View {
        if let document = PDFDocument(url: url) {
            PDFKitView(document: document)
                .ignoresSafeArea()
        } else {
            ContentUnavailableView("PDF kann nicht geladen werden", systemImage: "doc.questionmark")
        }
    }
}

Für interaktive Wrapper mit Seitenverfolgung, Annotationserkennung und Koordinator-Mustern siehe references/pdfkit-patterns.md.

Seitenüberlagerungen (iOS 16+)

Mit PDFPageOverlayViewProvider können UIKit-Ansichten über einzelne Seiten gelegt werden, z. B. für interaktive Steuerelemente oder benutzerdefinierte Darstellungen über Standardannotationen hinaus.

class OverlayProvider: NSObject, PDFPageOverlayViewProvider {
    func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? {
        let overlay = UIView()
        // Benutzerdefinierte Unteransichten hinzufügen
        return overlay
    }
}

pdfView.pageOverlayViewProvider = overlayProvider

Häufige Fehler

NICHT: PDFDocument-Init erzwingen (Force-Unwrap)

PDFDocument(url:) und PDFDocument(data:) sind fehlbare Initialisierer.

// FALSCH
let document = PDFDocument(url: url)!

// RICHTIG
guard let document = PDFDocument(url: url) else { return }

NICHT: autoScales auf PDFView vergessen

Ohne autoScales wird das PDF in seiner nativen Auflösung gerendert.

// FALSCH
pdfView.document = document

// RICHTIG
pdfView.autoScales = true
pdfView.document = document

NICHT: PDF-Koordinatensystem bei Annotationen ignorieren

PDF-Seitenkoordinaten haben den Ursprung unten links, wobei Y nach oben zeigt – umgekehrt zu UIKit.

// FALSCH: UIKit-Koordinaten
let bounds = CGRect(x: 50, y: 50, width: 200, height: 30)

// RICHTIG: PDF-Koordinaten (Ursprung unten links)
let pageBounds = page.bounds(for: .mediaBox)
let pdfY = pageBounds.height - 50 - 30
let bounds = CGRect(x: 50, y: pdfY, width: 200, height: 30)

NICHT: Annotationen in einem Hintergrund-Thread ändern

PDFKit-Klassen sind nicht threadsicher.

// FALSCH
DispatchQueue.global().async { page.addAnnotation(annotation) }

// RICHTIG
DispatchQueue.main.async { page.addAnnotation(annotation) }

NICHT: PDFDocument mit == in UIViewRepresentable vergleichen

PDFDocument ist ein Referenztyp. Verwenden Sie Identität (!==).

// FALSCH: Ersetzt immer das Dokument
func updateUIView(_ pdfView: PDFView, context: Context) {
    pdfView.document = document
}

// RICHTIG
func updateUIView(_ pdfView: PDFView, context: Context) {
    if pdfView.document !== document {
        pdfView.document = document
    }
}

Review-Checkliste

  • PDFDocument-Init verwendet optionales Binding, kein Force-Unwrap
  • pdfView.autoScales = true für korrekte Anfangsdarstellung gesetzt
  • Seitenindizes vor dem Zugriff gegen pageCount geprüft
  • displayMode und displayDirection entsprechend dem Design konfiguriert
  • Annotationen verwenden den PDF-Koordinatenraum (Ursprung unten links, Y nach oben)
  • Alle PDFKit-Änderungen erfolgen im Hauptthread
  • Passwortgeschützte PDFs mit isLocked / unlock(withPassword:) behandelt
  • SwiftUI-Wrapper verwendet !==-Identitätsprüfung in updateUIView
  • PDFViewPageChanged-Benachrichtigung für Seitenverfolgung beobachtet
  • PDFThumbnailView.pdfView mit dem Haupt-PDFView verknüpft
  • Suche in großen Dokumenten verwendet asynchrones beginFindString mit Delegate
  • Gespeicherte Dokumente verwenden write(to:withOptions:) bei Bedarf nach Verschlüsselung

Referenzen

Individual skills in this repo

This repo contains 11 individual skills — each has its own dedicated page.

JordanCoin/ios-skills-collection

Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries. Use when the user asks about GitHub issues, pull requests, workflows, or wants to interact with GitHub repositories from the command line — including tasks like check CI status, create PR, list issues, or query the GitHub API.

JordanCoin/ios-skills-collection

Create media playback experiences using AVKit. Use when adding video players with AVPlayerViewController, enabling Picture-in-Picture, routing media with AirPlay, using SwiftUI VideoPlayer views, configuring transport controls, displaying subtitles and closed captions, or integrating AVFoundation playback with system UI.

JordanCoin/ios-skills-collection

Integrate and optimize Core ML models in iOS apps for on-device machine learning inference. Covers model loading (.mlmodelc, .mlpackage), predictions with auto-generated classes and MLFeatureProvider, compute unit configuration (CPU, GPU, Neural Engine), MLTensor, VNCoreMLRequest, MLComputePlan, multi-model pipelines, and deployment strategies. Use when loading Core ML models, making predictions, configuring compute units, or profiling model performance.

JordanCoin/ios-skills-collection

Implement, review, or improve maps and location features in iOS/macOS apps using MapKit and CoreLocation. Use when working with Map views, annotations, markers, polylines, user location tracking, geocoding, reverse geocoding, search/autocomplete, directions and routes, geofencing, region monitoring, CLLocationUpdate async streams, or location authorization flows. Also use when working with maps, coordinates, addresses, places, directions, distance calculations, or location-based features in Swift apps.

JordanCoin/ios-skills-collection

Implement, review, or improve in-app tips and onboarding using Apple's TipKit framework. Use when adding feature discovery tooltips, onboarding flows, contextual tips, first-run experiences, coach marks, or working with Tip protocol, TipView, popoverTip, tip rules, tip events, or feature education UI.

JordanCoin/ios-skills-collection

When the user wants to optimize their Google Play Store listing — title, short description, full description, keywords, ratings, or Play Store-specific features. Use when the user mentions "Google Play", "Android", "Play Store", "Play Console", "short description", "full description indexed", "Google Play ASO", or wants Google Play-specific keyword, creative, or ratings strategy. For iOS App Store optimization, see aso-audit and metadata-optimization.

JordanCoin/ios-skills-collection

When the user wants to implement, optimize, or use App Clips for app discovery and conversion. Use when the user mentions "App Clip", "app clip code", "mini app", "instant app", "App Clip card", "App Clip link", "no download required", "instant experience", or wants to understand how App Clips appear in App Store search. For general App Store discoverability, see aso-audit. For marketing campaigns, see ua-campaign.

JordanCoin/ios-skills-collection

When the user wants to plan a launch strategy for a new app or major update. Also use when the user mentions "app launch", "launch plan", "launch checklist", "pre-launch", "launch day", or "how to launch my app". For ongoing ASO after launch, see aso-audit. For paid acquisition during launch, see ua-campaign.

JordanCoin/ios-skills-collection

When the user wants to analyze their own app's actual performance data from App Store Connect — real downloads, revenue, IAP, subscriptions, trials, or country breakdowns synced via Appeeky Connect. Use when the user asks about "my downloads", "my revenue", "how is my app performing", "ASC data", "sales and trends", "my subscription numbers", "App Store Connect metrics", or wants to compare periods or top markets. For third-party app estimates, see app-analytics. For subscription analytics depth, see monetization-strategy.

JordanCoin/ios-skills-collection

When the user wants a full ASO health audit, review their App Store listing quality, or diagnose why their app isn't ranking. Also use when the user mentions "ASO audit", "ASO score", "why am I not ranking", "listing review", or "optimize my app store page". For keyword-specific research, see keyword-research. For metadata writing, see metadata-optimization.

JordanCoin/ios-skills-collection

Always use when working on any iOS, macOS, Swift, SwiftUI, Xcode, or Apple platform project. Routes to the correct specialized skills based on development phase and task context. This collection contains 210 skills from 28 authors covering the full iOS lifecycle.

Verwandte Skills