macOS沙箱上的Swift文件读取权限错误 [英] Swift file reading permission error on macOS sandbox

查看:428
本文介绍了macOS沙箱上的Swift文件读取权限错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在macOS Swift应用程序(Xcode 9/Swift 4)中读取文件系统上文件的内容.

I'm trying to read the contents of a file on the filesystem in a macOS Swift app (Xcode 9 / Swift 4).

我正在使用以下代码段:

I'm using the following snippet for it:

let path = "/my/path/string.txt"
let s = try! String(contentsOfFile: path)
print(s)

我的问题如下:

  1. 这在游乐场
  2. 中有效
  3. 当我使用命令行工具 macOS应用模板
  4. 时,此方法有效
  5. 当我使用 Cocoa App macOS应用程序模板
  6. 时,这会终止权限错误
  1. This works in a Playground
  2. This works when I use the Command Line Tool macOS app template
  3. This terminates in a permission error when I use the Cocoa App macOS app template

权限错误如下:

致命错误:尝试!"表达式意外引发错误:

Fatal error: 'try!' expression unexpectedly raised an error:

Error Domain = NSCocoaErrorDomain Code = 257文件"data.txt"无法打开,因为您无权查看它."

Error Domain=NSCocoaErrorDomain Code=257 "The file "data.txt" couldn't be opened because you don't have permission to view it."

UserInfo = {NSFilePath =/my/path/data.txt,NSUnderlyingError = 0x60c0000449b0 {Error Domain = NSPOSIXErrorDomain Code = 1"不允许操作}}

UserInfo={NSFilePath=/my/path/data.txt, NSUnderlyingError=0x60c0000449b0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

我想它与沙箱有关,但是我没有找到有关它的信息.

I guess it's related to sandboxing but I found no information about it.

  1. 如何在沙盒应用程序中从文件系统读取?我的意思是,有太多需要打开文件对话框的GUI应用程序,这并不是对沙盒应用程序的现实限制,即不能从沙盒外部读取文件.

  1. How can I read from the filesystem in a sandboxed app? I mean there are so many GUI apps which need an Open File dialog, it cannot be a realistic restriction of sandboxed apps to not read files from outside the sandbox.

或者,如何在构建设置"中关闭沙箱?

Alternatively, how can I switch off sandboxing in Build Settings?

最后,我尝试比较默认Cocoa Apps和命令行工具模板之间的project.pbxproj文件,但没有看到任何有意义的区别,例如关于安全性或沙箱的区别.如果不在这里,这些设置存储在哪里?

Finally, I tried to compare the project.pbxproj files between the default Cocoa Apps and Command Line Tool template and I didn't see any meaningful difference, like something about security or sandbox. If not here, where are those settings stored?

推荐答案

您的项目符号1:您有答案,您需要使用NSOpenPanel来获得用户访问文件的权限.您可以使用NSOpenPanel方法将用户的选择限制在取消"按钮上,而仅限制在您想要的文件上,从而可以进行请求访问"对话框.首先 Apple的应用沙盒设计指南.

Your bullet 1: you have the answer, you need to use NSOpenPanel to obtain the user's permission to access the file. You can use NSOpenPanel methods to restrict the user's choice to the cancel button and just the file you wish - thus making a "request access to" dialog. Start with Apple's App Sandbox Design Guide.

项目符号2:您的想法正确,只是选项卡错误,您应该在摘要"选项卡上找到沙箱开关.

Your bullet 2: you've the right idea, just the wrong tab, you should find the sandboxing switch on the Summary tab.

HTH

这篇关于macOS沙箱上的Swift文件读取权限错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆