无法在真实设备上获取文件内容swift 文件基础应用程序

问题描述

我有一个基于文件的应用程序,可以打开源代码。这是我用于它的函数

func presentDocument(at documentURL: URL) {
    
    let storyBoard = UIStoryboard(name: "Main",bundle: nil)
    let documentViewNavController = storyBoard.instantiateViewController(withIdentifier: "documentNavVc")
    
    do {
        
        let text =  try String(contentsOf: documentURL,encoding: .utf8)
        let name = documentURL.lastPathComponent
        if let documentViewController = documentViewNavController.contents as? DocumentViewController{
            documentViewController.text = text
            documentViewController.title = name
        }
        
    }
    catch {
        print(error.localizedDescription)
    }
    
    documentViewNavController.modalPresentationStyle = .fullScreen
    
    present(documentViewNavController,animated: true,completion: nil)
}

}

所以问题是在模拟器上它可以完美运行,但是在真实设备上,它在尝试获取文件内容并打印此错误后会捕获块并打印此错误:无法打开文件,因为您没有没有权限查看。

可能是因为我没有征求用户的许可才能使用文件浏览器(我不知道)

这里有什么解决方案吗?

解决方法

您尝试读取的 URL 是什么?

对于非越狱设备,每个应用程序都有一个沙盒目录(称为文档目录),您可以在其中存储和读取的文件。

要从添加到项目文件中读取,您需要确保在构建阶段将其添加到目标和复制捆绑资源阶段。这样,文件将被添加到将安装在设备上的应用程序包中。然后您可以简单地通过文件名称访问您的文件。

,

所以解决方案是打开受保护的文件(所有文件,除了你的应用程序文件夹中的文件都是安全的),这篇文章帮助了我 https://developer.apple.com/documentation/uikit/view_controllers/providing_access_to_directories