Swift - 在模拟器中获取 PDF 数据,但不能在真正的 iPhone 上运行

问题描述

我有一个非常简单的应用程序,带有一个按钮,可以打开文件应用程序并在控制台中打印 PDF 的内容。这在模拟器上完美运行,但在真正的 iOS 设备上使用该应用程序时,该应用程序不会打印任何内容


import PDFKit

 @State var openFile = false

  Button(action:{
                openFile.toggle()
            }){
                
                Image(systemName: "exclamationmark.circle.fill")
            }
        }
        .fileImporter(isPresented: $openFile,allowedContentTypes: [.pdf],onCompletion: {result in
                        if let fileURL = try? result.get() {
                            print(fileURL)
                            if let pdf = PDFDocument(url: fileURL) {
                                print(pdf)
                                let pageCount = pdf.pageCount
                                print(pdf.pageCount)
                                let documentContent = NSMutableAttributedString()

                                for i in 0 ..< pageCount {
                                    guard let page = pdf.page(at: i) else { continue }
                                    guard let pageContent = page.attributedString else { continue }
                                    documentContent.append(pageContent)
                                }
                               
                                print(documentContent.string)
                            }
                            
                        }
                      })

Info.plist 中,我已经添加了密钥 Supports opening documents in placeApplication supports iTunes file sharing,但是我找不到任何东西让它在真实设备中工作。

提前感谢您的支持

解决方法

找到答案了!

if let 更改为 guard let 添加了 fileURL.startAccessingSecurityScopedResource()fileURL.stopAccessingSecurityScopedResource()

 Button(action:{
                openFile.toggle()

                
            }){
                
                Image(systemName: "exclamationmark.circle.fill")
            }
        }.fileImporter(
            isPresented: $openFile,allowedContentTypes: [.pdf],allowsMultipleSelection: false
        ) { result in
            do {

                guard let fileURL: URL = try result.get().first else { return print("error fileURL") }
                fileURL.startAccessingSecurityScopedResource()
                guard let pdf = PDFDocument.init(url: fileURL) else {return print("error pdf")}
                let pageCount = pdf.pageCount
                let documentContent = NSMutableAttributedString()
                
                for i in 0..<pageCount {
                    guard let page = pdf.page(at: i) else { continue }
                    guard let pageContent = page.attributedString else { continue }
                    documentContent.append(pageContent)
                }
                fileURL.stopAccessingSecurityScopedResource()
                print(documentContent.string)
               
            } catch {
                print(error)
            }
        }