Communitygithub.com

JordanCoin/ios-skills-collection

Exibe e manipula documentos PDF usando PDFKit. Use ao incorporar PDFView para mostrar arquivos PDF, criar ou modificar instâncias de PDFDocument, adicionar anotações (destaques, notas, assinaturas), extrair texto com PDFSelection, navegar por páginas, gerar miniaturas, preencher formulários PDF ou integrar PDFView no SwiftUI.

O que é ios-skills-collection?

Esta habilidade fornece um guia completo e prático para utilizar o framework PDFKit da Apple em plataformas iOS, iPadOS, macOS e visionOS, com foco em Swift 6.3 e iOS 26+. Ela cobre desde a configuração básica até técnicas avançadas de integração com SwiftUI. O conteúdo aborda a exibição de PDFs com PDFView, incluindo modos de exibição (página única, contínuo, duas páginas), carregamento de documentos a partir de URLs ou dados, navegação entre páginas com histórico, busca e extração de texto (síncrona e assíncrona), criação e gerenciamento de anotações como destaques, notas adesivas e links, e geração de miniaturas. Inclui também padrões de integração com SwiftUI através de UIViewRepresentable e overlays de página com iOS 16+. A habilidade é útil para desenvolvedores que precisam implementar visualizadores de PDF ricos em funcionalidades, com ênfase em boas práticas e alertas sobre erros comuns.

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

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

PDFKit

Exiba, navegue, pesquise, anote e manipule documentos PDF com PDFView, PDFDocument, PDFPage, PDFAnnotation e PDFSelection. Alvo: Swift 6.3 / iOS 26+.

Conteúdo

Configuração

PDFKit não requer entitlements ou entradas no Info.plist.

import PDFKit

Disponibilidade de plataforma: iOS 11+, iPadOS 11+, Mac Catalyst 13.1+, macOS 10.4+, tvOS 11+, visionOS 1.0+.

Exibindo PDFs

PDFView é uma subclasse de UIView que renderiza conteúdo PDF, lida com zoom, rolagem, seleção de texto e navegação entre páginas prontamente.

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)
        }
    }
}

Modos de Exibição

ModoComportamento
.singlePageUma página por vez
.singlePageContinuousPáginas empilhadas verticalmente, roláveis
.twoUpDuas páginas lado a lado
.twoUpContinuousDuas páginas com rolagem contínua

Escala e Aparência

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

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

Carregando Documentos

PDFDocument carrega a partir de uma URL, Data, ou pode ser criado vazio.

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

PDFs Protegidos por Senha

guard let document = PDFDocument(url: url) else { return }
if document.isLocked {
    if !document.unlock(withPassword: userPassword) {
        // Mostrar prompt de senha
    }
}

Salvando e Manipulando Páginas

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

// Páginas (base 0)
let count = document.pageCount
document.insert(PDFPage(), at: count)
document.removePage(at: 2)
document.exchangePage(at: 0, withPageAt: 3)

Navegação entre Páginas

PDFView fornece navegação integrada com histórico.

// Ir para uma página específica
if let page = pdfView.document?.page(at: 5) {
    pdfView.go(to: page)
}

// Navegação sequencial
pdfView.goToNextPage(nil)
pdfView.goToPreviousPage(nil)
pdfView.goToFirstPage(nil)
pdfView.goToLastPage(nil)

// Verificar estado da navegação
if pdfView.canGoToNextPage { /* ... */ }

// Navegação pelo histórico
if pdfView.canGoBack { pdfView.goBack(nil) }

// Ir para um ponto específico em uma página
let destination = PDFDestination(page: page, at: CGPoint(x: 0, y: 500))
pdfView.go(to: destination)

Observando Mudanças de Página

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 = "Página \(index + 1) de \(doc.pageCount)"
}

Busca e Seleção de Texto

Busca Síncrona

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

Busca Assíncrona

Use PDFDocumentDelegate para buscas em segundo plano em documentos grandes. Implemente didMatchString(_:) para receber cada correspondência e documentDidEndDocumentFind(_:) para conclusão.

Busca Incremental e Interação de Localizar

// Encontrar próxima correspondência a partir da seleção atual
let next = document.findString("termo", fromSelection: current, withOptions: [.caseInsensitive])

// Barra de localizar do sistema (iOS 16+)
pdfView.isFindInteractionEnabled = true

Extração de Texto

let fullText = document.string                          // Documento inteiro
let pageText = document.page(at: 0)?.string             // Página única
let attributed = document.page(at: 0)?.attributedString  // Com formatação

// Extração baseada em região
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
}

Destacando Resultados de Busca

let results = document.findString("importante", 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)
}

Anotações

Anotações são criadas com PDFAnnotation(bounds:forType:withProperties:) e adicionadas a uma PDFPage.

Anotação de Destaque

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)
}

Anotação de Nota de Texto

let note = PDFAnnotation(
    bounds: CGRect(x: 100, y: 700, width: 30, height: 30),
    forType: .text, withProperties: nil
)
note.contents = "Esta é uma nota adesiva."
note.color = .systemYellow
note.iconType = .comment
page.addAnnotation(note)

Anotação de Texto Livre

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

Anotação de Link

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)

// Link para página interna
link.destination = PDFDestination(page: targetPage, at: .zero)

Removendo Anotações

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

Referência de Subtipos de Anotação

SubtipoConstantePropósito
Destaque.highlightMarcação de texto (destaque amarelo)
Sublinhado.underlineMarcação de texto (sublinhado)
Tachado.strikeOutMarcação de texto (tachado)
Texto.textÍcone de nota adesiva
TextoLivre.freeTextBloco de texto inline
Tinta.inkTraços de desenho à mão livre
Link.linkURL ou destino de página
Linha.lineLinha reta com pontos finais
Quadrado.squareForma retangular
Círculo.circleForma elíptica
Carimbo.stampCarimbo (Aprovado, etc.)
Widget.widgetElemento de formulário (campo de texto, caixa de seleção)

Miniaturas

PDFThumbnailView

PDFThumbnailView mostra uma faixa de miniaturas de página vinculadas a um PDFView.

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

Gerando Miniaturas Programaticamente

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

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

Integração com SwiftUI

Envolva PDFView em um UIViewRepresentable para 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
        }
    }
}

Uso

struct DocumentScreen: View {
    let url: URL

    var body: some View {
        if let document = PDFDocument(url: url) {
            PDFKitView(document: document)
                .ignoresSafeArea()
        } else {
            ContentUnavailableView("Não foi possível carregar o PDF", systemImage: "doc.questionmark")
        }
    }
}

Para wrappers interativos com rastreamento de página, detecção de toque em anotações e padrões de coordenador, veja references/pdfkit-patterns.md.

Sobreposições de Página (iOS 16+)

PDFPageOverlayViewProvider coloca visualizações UIKit sobre páginas individuais para controles interativos ou renderização personalizada além das anotações padrão.

class OverlayProvider: NSObject, PDFPageOverlayViewProvider {
    func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? {
        let overlay = UIView()
        // Adicionar subvisualizações personalizadas
        return overlay
    }
}

pdfView.pageOverlayViewProvider = overlayProvider

Erros Comuns

NÃO FAÇA: Forçar desempacotamento do init de PDFDocument

PDFDocument(url:) e PDFDocument(data:) são inicializadores falíveis.

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

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

NÃO FAÇA: Esquecer autoScales no PDFView

Sem autoScales, o PDF renderiza em sua resolução nativa.

// ERRADO
pdfView.document = document

// CORRETO
pdfView.autoScales = true
pdfView.document = document

NÃO FAÇA: Ignorar o sistema de coordenadas PDF em anotações

As coordenadas de página PDF têm origem no canto inferior esquerdo com Y aumentando para cima — oposto ao UIKit.

// ERRADO: Coordenadas UIKit
let bounds = CGRect(x: 50, y: 50, width: 200, height: 30)

// CORRETO: Coordenadas PDF (origem canto inferior esquerdo)
let pageBounds = page.bounds(for: .mediaBox)
let pdfY = pageBounds.height - 50 - 30
let bounds = CGRect(x: 50, y: pdfY, width: 200, height: 30)

NÃO FAÇA: Modificar anotações em uma thread de segundo plano

As classes PDFKit não são thread-safe.

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

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

NÃO FAÇA: Comparar PDFDocument com == em UIViewRepresentable

PDFDocument é um tipo de referência. Use identidade (!==).

// ERRADO: Sempre substitui o documento
func updateUIView(_ pdfView: PDFView, context: Context) {
    pdfView.document = document
}

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

Lista de Verificação de Revisão

  • PDFDocument init usa ligação opcional, não força desempacotamento
  • pdfView.autoScales = true definido para exibição inicial adequada
  • Índices de página verificados em relação a pageCount antes do acesso
  • displayMode e displayDirection configurados para corresponder ao design
  • Anotações usam o espaço de coordenadas PDF (origem no canto inferior esquerdo, Y para cima)
  • Todas as mutações do PDFKit ocorrem na thread principal
  • PDFs protegidos por senha tratados com isLocked / unlock(withPassword:)
  • Wrapper SwiftUI usa verificação de identidade !== em updateUIView
  • Notificação PDFViewPageChanged observada para rastreamento de página
  • PDFThumbnailView.pdfView vinculado ao PDFView principal
  • Busca em documentos grandes usa beginFindString assíncrono com delegate
  • Documentos salvos usam write(to:withOptions:) quando a criptografia é necessária

Referências

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.

Habilidades Relacionadas