从桌面加载 NSImage 在 cocoa 应用程序中为零

NSImage loading from desktop getting nil in cocoa app

您好,我正在尝试加载位于桌面的图像。

NSURL *imageURL = [[NSWorkspace sharedWorkspace] desktopImageURLForScreen:[NSScreen mainScreen]];
 NSLog(@"%@",imageURL);
 NSImage *testImage = [[NSImage alloc] initWithContentsOfURL:imageURL];
 NSLog(@"%@",testImage);
[self.desktopView setImage:testImage];

testImage 日志 (null)

我正在使用上面的代码,但测试图像变为零。

有什么建议吗?

提前致谢!

您可能在功能中启用了 App Sandbox(我相信它是默认启用的)。启用它后,如果没有用户交互(即 NSOpenPanel or NSSavePanel),您将无法访问应用程序容器(或某些其他指定位置)之外的文件。

文件系统编程指南:https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html

App Sandbox 文档在这里:https://developer.apple.com/library/archive/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html

如果您想禁用 App Sandbox,可以通过单击您的项目文件 > 目标名称,选择功能选项卡并关闭 App Sandbox 来关闭它。

编辑:

您将要使用安全范围的书签来进行持久的资源访问。我不熟悉你评论中的应用程序,但我猜他们会首先提示用户 运行 进行访问。

此处的文档:

https://developer.apple.com/library/archive/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16

https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html#//apple_ref/doc/uid/TP40011195-CH4-SW18