如何在应用程序中从 Xcode 的“支持文件”组访问文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7686420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I access a file from Xcode’s "Supporting Files" group, in app?
提问by zeroCube
I have an app that I've almost finish now that emails, at the end of a data entry flow, two .pdf files. One of these is generated from the entered data, the other is a static file that will be the same in every instance.
我有一个应用程序,我现在快完成了,它在数据输入流程的末尾发送电子邮件,两个 .pdf 文件。其中一个是根据输入的数据生成的,另一个是在每个实例中都相同的静态文件。
The first pdf is generating fine, it's saved to the apps 'documents' folder, and I have successfully attached to to an email for sending. It's the second .pdf, one that I made externally to the app and am trying to add, that is causing me grief.
第一个 pdf 生成得很好,它保存到应用程序的“文档”文件夹中,我已成功附加到电子邮件中进行发送。这是第二个 .pdf,我在应用程序外部制作并试图添加的第二个 .pdf,这让我很伤心。
I've added it to the 'Supporting Files' folder within my Xcode project, but after much searching on here, and elsewhere online, I can't work out how to access that file to be able to add it as an attachment in the email. Having "downloaded" the app's data from the Organizer in Xcode, I can see that the file isn't there anywhere; presumably because Xcode can see that the file isn't being used anywhere, it's not adding it at build time (very much an assumption on my part), but I don't know how to reference it anywhere because I don't know where it will be to reference it!
我已将它添加到我的 Xcode 项目中的“支持文件”文件夹中,但是在此处和在线其他地方进行了大量搜索后,我无法弄清楚如何访问该文件以将其作为附件添加到电子邮件。从 Xcode 的 Organizer 中“下载”了应用程序的数据后,我可以看到该文件不在任何地方;大概是因为 Xcode 可以看到该文件没有在任何地方使用,它没有在构建时添加它(我的假设非常重要),但我不知道如何在任何地方引用它,因为我不知道在哪里它会参考它!
回答by mja
The Xcode does not generate any folders in your app bundle that corresponds to groups. Just make sure that your pdf is present in Copy Bundle Resources in your target's Build Phases. You then access your resource under [[NSBundle mainBundle] bundlePath]
path.
Xcode 不会在您的应用程序包中生成与组对应的任何文件夹。只需确保您的 pdf 出现在目标构建阶段的 Copy Bundle Resources 中。然后,您可以在[[NSBundle mainBundle] bundlePath]
路径下访问您的资源。
回答by Hieu Pious
If you want to access an image, this code is a good sample as how to:
如果您想访问图像,此代码是一个很好的示例,说明如何:
NSString* imageName = [[NSBundle mainBundle] pathForResource:@"image1" ofType:@"png"];
NSImage* imageObj = [[NSImage alloc] initWithContentsOfFile:imageName];
回答by j.s.com
In Swift you can get the bundle-resorce-path with the following function:
在 Swift 中,您可以使用以下函数获取 bundle-reorce-path:
func currentresourcepath () -> String
{
return (NSBundle.mainBundle().bundlePath + "/Contents/Resources/")
}