Loading PDF Document for View

I am trying to open a stored PDF-Document in my Viewer. I create it in my View and as long as don’t switch out of this DetailView I can open the PDF in the sheet as often as I like. When I go out of the detail back to the list and reopen the same detail, the sheet shows that the pdf-file not exist.

in the console I got the following print out:

`Dateiname: 05489A28-2BFE-4981-A2FE-434A6C2673CA.pdf
Lade PDF von: file:///Users/roland/Library/Developer/CoreSimulator/Devices/2F2C7651-340C-4A5B-B678-5F52FE0910AD/data/Containers/Data/Application/48DDC047-E7B4-4F7E-B5F9-FE250677409A/Documents/05489A28-2BFE-4981-A2FE-434A6C2673CA.pdf
PDF-Daten erfolgreich geladen`

Here are the affected parts of my application

@State private var pdfData: Data?
@State private var showingPDF = false

HStack {
                    Text("Dateiname: (workReport.pdfFileName ?? "")")
                    Spacer()
                    Button(action: {
                        print("Dateiname: (workReport.pdfFileName ?? "")")
                        if let fileName = workReport.pdfFileName {
                            loadPDFData(fileName: fileName)
                        }
                    }) {
                        Image(systemName: "doc.richtext")
                            .foregroundColor(.blue)
                    }
                }

This is my function

func loadPDFData(fileName: String) {
    let fileURL = documentModel.getDocumentsDirectory().appendingPathComponent(fileName)
    print("Lade PDF von: (fileURL)") // Debugging-Ausgabe
    
    DispatchQueue.global(qos: .background).async {
        do {
            let pdfData = try Data(contentsOf: fileURL)
            DispatchQueue.main.async {
                self.pdfData = pdfData
                print("PDF-Daten erfolgreich geladen") // Debugging-Ausgabe
                if pdfData.count > 0 {
                    self.showingPDF = true
                } else {
                    print("Geladene PDF-Daten sind leer")
                }
            }
        } catch {
            DispatchQueue.main.async {
                self.pdfData = nil
                print("Fehler beim Laden der PDF-Daten: (error.localizedDescription)")
            }
        }
    }
}

When I set the breakpoint in the loadPDFData, then everything looks fine. i can make po pdfData.count and it gives me a result. In the finder I can select the PDF-File and open it without a error.

In this function i come in the if pdfData.count > 0 and so the sheet would be opened.

This is the sheet:

    .sheet(isPresented: $showingPDF) {
        if let pdfData = pdfData, pdfData.count > 0 {
            PDFViewer(pdfData: pdfData)
        } else {
            Text("Keine PDF-Daten verfügbar")
        }
    }

But it show me the else path

It seems that pdfData lost its content.

Here I show you the full View:

import SwiftUI
import CoreData

struct CustomerOrderWorkReportDetailView: View {
@Environment(.managedObjectContext) private var viewContext

var workReport: CustomerOrderWorkReports
@ObservedObject var customerOrderWorkReportItemModel: CustomerOrderWorkReportItemModel
@ObservedObject var customerOrderWorkReportWorktimeModel: CustomerOrderWorkReportWorktimeModel
@StateObject private var documentModel: CustomerDocumentModel
@StateObject private var customerOrderWorkReportModel: CustomerOrderWorkReportModel

@State private var showingAddSheet: Bool = false
@State private var showingWorktimeAddEditSheet: Bool = false
@State private var showingSignatureSheet: Bool = false
@State private var isSignatureExpanded: Bool = false
@State private var showingUnsignAlert: Bool = false

@State private var annotation: String = ""

@State private var signerName: String = ""
@StateObject private var viewModel = SignatureViewModel()

// PDF
@State private var pdfData: Data?
@State private var showingPDF = false

init(workReport: CustomerOrderWorkReports, customerOrderWorkReportItemModel: CustomerOrderWorkReportItemModel, customerOrderWorkReportWorktimeModel: CustomerOrderWorkReportWorktimeModel, customerOrderWorkReportModel: CustomerOrderWorkReportModel) {
    self.workReport = workReport
    self.customerOrderWorkReportItemModel = customerOrderWorkReportItemModel
    self.customerOrderWorkReportWorktimeModel = customerOrderWorkReportWorktimeModel
    self._documentModel = StateObject(wrappedValue: CustomerDocumentModel(context: PersistenceController.shared.container.viewContext, customerID: workReport.customerID ?? ""))
    self._customerOrderWorkReportModel = StateObject(wrappedValue: customerOrderWorkReportModel)
}

var body: some View {
    Form {
        Section {
            Text("(NSLocalizedString("date", comment: "Datum")): (workReport.addDate != nil ? DateFormatter.shortDateFormatter.string(from: workReport.addDate!) : "N/A")")
            if workReport.isSigned, let signDate = workReport.signDate {
                Text("(NSLocalizedString("signed date", comment: "Unterschriftsdatum")): (signDate)")
                Text(workReport.annotation ?? "")
                HStack {
                    Text("Dateiname: (workReport.pdfFileName ?? "")")
                    Spacer()
                    Button(action: {
                        print("Dateiname: (workReport.pdfFileName ?? "")")
                        if let fileName = workReport.pdfFileName {
                            loadPDFData(fileName: fileName)
                        }
                    }) {
                        Image(systemName: "doc.richtext")
                            .foregroundColor(.blue)
                    }
                }
                
                Toggle(isOn: Binding(
                    get: { workReport.isSigned },
                    set: { newValue in
                        if !newValue {
                            showingUnsignAlert = true
                        }
                    }
                )) {
                    Text("Ist unterschrieben")
                }
            }
        }
        
        Section(header: Text("Positionen")) {
            ForEach(customerOrderWorkReportItemModel.orderWorkReportItemList, id: .self) { item in
                itemView(item: item)
            }
            .onDelete(perform: deleteItems)
            .disabled(workReport.isSigned)
        }
        
        Section(header: Text("Arbeitszeit")) {
            ForEach(customerOrderWorkReportWorktimeModel.orderWorkReportWorktimeList, id: .self) { worktimeItem in
                worktimeItemView(worktimeItem: worktimeItem)
            }
            
            if !workReport.isSigned {
                Button(action: {
                    showingWorktimeAddEditSheet = true
                }) {
                    Label("Arbeitszeit hinzufügen", systemImage: "clock")
                }
                .sheet(isPresented: $showingWorktimeAddEditSheet) {
                    CustomerOrderWorkReportWorktimeAddEditView(
                        customerWorkReportWorktime: customerOrderWorkReportWorktimeModel,
                        item: nil,  // nil, wenn eine neue Arbeitszeit hinzugefügt wird
                        customerID: workReport.customerID ?? "",
                        customerOrderID: workReport.customerOrderID ?? "",
                        customerOrderWorkReportID: workReport.uniqueID ?? ""
                    )
                }
            }
        }
        
        if !workReport.isSigned {
            Section {
                DisclosureGroup(isExpanded: $isSignatureExpanded) {
                    VStack {
                        TextField("Anmerkungen", text: $annotation)
                        
                        TextField("Name des Unterzeichners", text: $signerName)
                            .textFieldStyle(RoundedBorderTextFieldStyle())
                            .padding()
                        
                        Canvas { context, size in
                            for path in viewModel.paths {
                                context.stroke(path, with: .color(.black), lineWidth: 3)
                            }
                        }
                        .gesture(DragGesture(minimumDistance: 0, coordinateSpace: .local)
                            .onChanged { value in
                                let newPoint = value.location
                                if value.translation.width + value.translation.height == 0 {
                                    viewModel.addNewPath(at: newPoint)
                                } else {
                                    viewModel.addPoint(newPoint)
                                }
                            })
                        .frame(height: 120)
                        .background(Color.white)
                        .cornerRadius(10)
                        .shadow(radius: 5)
                        
                        Button("Bestätigen") {
                            handleSignature(paths: viewModel.paths, signerName: signerName, annotation: annotation)
                            isSignatureExpanded = false // Klappe die Gruppe nach der Bestätigung zusammen
                        }
                        .padding()
                        
                    }
                } label: {
                    Label("Unterschrift erfassen", systemImage: isSignatureExpanded ? "chevron.up" : "chevron.down")
                }
            }
        }
    }
    .navigationTitle("(NSLocalizedString("workreport", comment: "Regiebericht"))")
    .toolbar {
        if !workReport.isSigned {
            ToolbarItem(placement: .navigationBarTrailing) {
                Button(action: {
                    showingAddSheet = true
                }) {
                    Label(NSLocalizedString("add", comment: "Neue Position"), systemImage: "plus")
                }
                .sheet(isPresented: $showingAddSheet) {
                    CustomerOrderWorkReportItemAddEditView(
                        customerReportItemModel: customerOrderWorkReportItemModel,
                        item: nil, // selectedItem sollte die ausgewählte Instanz sein
                        customerID: workReport.customerID ?? "",
                        customerOrderID: workReport.customerOrderID ?? "",
                        customerOrderWorkReportID: workReport.uniqueID ?? "")
                }
            }
        }
    }
    .sheet(isPresented: $showingPDF) {
        if let pdfData = pdfData, pdfData.count > 0 {
            PDFViewer(pdfData: pdfData)
        } else {
            Text("Keine PDF-Daten verfügbar")
        }
    }
    .alert(isPresented: $showingUnsignAlert) {
        Alert(
            title: Text("Warnung"),
            message: Text("Das Zurücksetzen der Unterschrift wird das unterschriebene PDF löschen. Fortfahren?"),
            primaryButton: .destructive(Text("Weiter"), action: {
                unsignReport()
            }),
            secondaryButton: .cancel(Text("Abbrechen"))
        )
    }
}


func loadPDFData(fileName: String) {
    let fileURL = documentModel.getDocumentsDirectory().appendingPathComponent(fileName)
    print("Lade PDF von: (fileURL)") // Debugging-Ausgabe
    
    DispatchQueue.global(qos: .background).async {
        do {
            let pdfData = try Data(contentsOf: fileURL)
            DispatchQueue.main.async {
                self.pdfData = pdfData
                print("PDF-Daten erfolgreich geladen") // Debugging-Ausgabe
                if pdfData.count > 0 {
                    self.showingPDF = true
                } else {
                    print("Geladene PDF-Daten sind leer")
                }
            }
        } catch {
            DispatchQueue.main.async {
                self.pdfData = nil
                print("Fehler beim Laden der PDF-Daten: (error.localizedDescription)")
            }
        }
    }
}
}

I recoded and try to debug with breakpoints again and again

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật