从扩展中读取和写入iOS应用程序文档文件夹

我正在开发一个具有动作扩展的Objective-C iOS应用程序。 当动作扩展加载时,我需要从主机应用程序的文档目录中读取一些文件,然后将文件写入主机应用程序文档目录。 我已经创build了一个应用程序组,并且应用程序和扩展都具有该应用程序组。 但是,设置后,我仍然不知道如何从扩展名的主机应用程序文档文件夹读取和写入文件。 有任何想法吗?

谢谢,

玩笑

您不能直接写入主机应用程序本身。 应用程序组允许您访问iOS应用程序和扩展程序可访问的共享文件系统容器。

要获得共享文件系统根文件夹的NSURL ,请使用以下调用:

 NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.something")` 

例如: 存储和读取图像文件

 // store // goal: move image located in main bundle to shared documents folder // so that extension can access the image NSString *gifPath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"gif"]; // located in main bundle NSData *gifData = [NSData dataWithContentsOfFile:gifPath]; // image data // get the path of shared folder NSString *destinationPath = [[[[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"app.group-name"] path] stringByAppendingPathComponent:@"image.gif"]; // where to store your image [gifData writeToFile:destinationPath atomically:YES]; // write to shared document folder // load NSData *storedImage; // get shared document folders path NSString *path = [[[[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:kKeyboardSuiteName] path] stringByAppendingPathComponent:@"image.gif"]]; storedImage = [NSData dataWithContentsOfFile:path]; //load image 

虽然使用“containerURLForSecurityApplicationGroupIdentifier”是首选,而且根本不复杂,但实际上可以通过在Extension中的主应用程序中调用ViewController来从文档目录读取和写入:

喜欢:

 MainViewController * mvc = [MainViewController alloc]init]; NSData * theFile =[mvc readFileFromDocFolder];