I am developing an objective-c iOS application that has an action extension. When the action extension loads I need to read some files from the documents directory of the host application and then write a file to the host applications document directory. I have created an application group and both the application and the extension have that application group set. But, after setting it I still not figure out how to read and write the files from the host applications document folder from the extension. Any ideas?
Thanks,
Josh
You cannot write to the host application itself directly. Application Group gives you access to shared filesystem container accessible by both iOS app and Extension.
To get URL
of that shared filesystem root folder, use this call:
FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.something")
For example: Store and read image file
// 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
While using the "containerURLForSecurityApplicationGroupIdentifier" is preferred and not complex at all, you can actually read and write from the Document Directory, by calling a ViewController in the main App from the Extension:
like:
MainViewController * mvc = [MainViewController alloc]init];
NSData * theFile =[mvc readFileFromDocFolder];