CodexBloom - Programming Q&A Platform

Difficulty Fetching and Displaying PDF from URL in SwiftUI on iOS 17

👀 Views: 10 đŸ’Ŧ Answers: 1 📅 Created: 2025-09-06
swift swiftui pdfkit Swift

I've looked through the documentation and I'm still confused about I tried several approaches but none seem to work... I need some guidance on I'm stuck on something that should probably be simple... I'm stuck on something that should probably be simple... Currently developing an app that needs to display a PDF from a remote URL. I've set up a view where I use `PDFKit` to handle the PDF rendering, but I keep hitting a roadblock when trying to fetch the data asynchronously. Using `URLSession`, I try to load the PDF, but it seems like the data isn't being passed correctly to the `PDFView`. Here's what my code looks like: ```swift import SwiftUI import PDFKit struct PDFViewWrapper: UIViewRepresentable { var url: URL? func makeUIView(context: Context) -> PDFView { return PDFView() } func updateUIView(_ uiView: PDFView, context: Context) { guard let url = url else { return } let request = URLRequest(url: url) URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("Error fetching PDF: \(error.localizedDescription)") return } guard let data = data else { print("No data returned") return } if let document = PDFDocument(data: data) { DispatchQueue.main.async { uiView.document = document } } else { print("Failed to create PDFDocument") } }.resume() } } struct ContentView: View { var body: some View { PDFViewWrapper(url: URL(string: "https://example.com/sample.pdf")) .frame(width: 400, height: 600) } } ``` After fetching, I expect the PDF to display, but the `PDFView` remains empty. There's no error printed, but I suspect the `updateUIView` method isn't triggering the `PDFDocument` correctly. I've also checked that the URL is valid, and I can confirm that the PDF file is accessible via a web browser. Any advice on how to ensure the PDF loads correctly? Is there something I'm missing regarding the threading? Or maybe an issue with how SwiftUI handles the `UIViewRepresentable` lifecycle? I'd really appreciate any guidance on this. This is my first time working with Swift stable. Is there a better approach? I'm working with Swift in a Docker container on Windows 10. Any examples would be super helpful. The stack includes Swift and several other technologies.