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

Couldn't get files contents on a real device (swift file base app)

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

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)
}

}

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

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

这里有什么解决办法吗?

您要阅读的 URL 是什么?

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

要从添加到项目文件中读取,您需要确保它已添加到构建阶段的目标和Copy Bundle Resources阶段。这样,该文件将被添加到将安装在设备上的应用程序包中。然后,您只需通过文件名即可访问您的文件。

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