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