英文:
I cannot set permissions to read a file in my project directory using Xcode 14 and Swift 5 on macOS Ventura
问题
我正在编写一个最小的应用程序,用于学习如何读取UInt16数据并将其显示为图像。最终编译成功,但在运行时出现文件读取权限错误。我尝试给应用程序授予读写文件的权限,权限似乎显示我有读写权限。
它在第二行崩溃:
let fileURL = URL(fileURLWithPath: "/Users/<user>/<some path/<some file with ext .raw>")
let data = try! Data(contentsOf: fileURL)
出现以下错误:
线程1:致命错误:'try!'表达式意外引发错误:错误域=NSCocoaErrorDomain Code=257 "由于您没有权限查看它,无法打开文件“p03-4M1-041.raw”" UserInfo={NSFilePath=/Users/nate/2008 11 15 Freeway Fire/p03/p03-4M1-041.raw, NSUnderlyingError=0x600002d72a90 {Error Domain=NSPOSIXErrorDomain Code=1 "操作不允许"}}
我认为这是Xcode的问题,因为Assets.xcassets似乎是空的,而且没有plist。
我正在使用Xcode 14,Swift5,在我的macBook上运行Ventura。
英文:
I'm writing a minimal app to learn how to read a file with UInt16 data that can be displayed as an image. It finally compiles but crashes at runtime with a file read permission error. I've attempted to give the app permission for read and write files, the permissions appear to say that I have read and write permissions.
It crashes on the second line:
let fileURL = URL(fileURLWithPath: "/Users/<user>/<some path/<some file with ext .raw>")
let data = try! Data(contentsOf: fileURL)
with this error:
>Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=257 "The file “p03-4M1-041.raw” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/Users/nate/2008 11 15 Freeway Fire/p03/p03-4M1-041.raw, NSUnderlyingError=0x600002d72a90 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
I think that this is an Xcode problem as the Assets.xcasssets appears to be empty and there is no plist.
I'm using Xcode 14, Swift5, on my macBook running Ventura.
答案1
得分: 1
macOS应用程序是受沙盒限制的。要访问应用程序资源包之外的文件,您需要在项目的目标上的“签名和功能”选项卡的“App沙盒”部分启用“用户选择的文件”文件访问权限。
然后,您需要使用标准文件选择器(例如NSOpenPanel
)。然后,您的应用程序将被授予访问所选文件的权限。您不能访问您创建文件URL的任意文件。
除了启用“用户选择的文件”外,您还可以授予对标准文件夹(如“Downloads”和其他一些文件夹)的访问权限。然后,您的应用程序可以直接访问已被授予访问权限的文件夹中的文件。
英文:
A macOS app is sandboxed. To access files outside of your app's resource bundle you would need to enable the "User Selected File" file access permission in the App Sandbox section of your project's target on the "Signing and Capabilities" tab.
You would then need use the standard file chooser (such as NSOpenPanel
). Then your app would have permission to access just the selected file(s). You can't access any arbitrary file you happen to create a file URL for.
Besides enabling "User Selected File", you can also grant access to standard folders such as "Downloads" and a few others. Then your app could directly access files in the folders your app has been granted access to.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论