Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing data in the documents directory in iPhone and Watch app

Tags:

ios

watchkit

How do I use App Groups to share data, such as images, in the documents directory?

If this is not possible what is the best way to share images between the Watch App and the iPhone app? I can store the image binary data in coredata but this is not very efficient. I can also accomplish this using NSUserDefaults but again this is not efficient.

like image 720
James Avatar asked Jan 09 '23 08:01

James


1 Answers

After you've configured your App Group in Xcode (see the section on Sharing Data with Your Containing iOS App), you can obtain a path to the shared container/folder like this:

NSURL *groupContainerURL = [[NSFileManager defaultManager]
            containerURLForSecurityApplicationGroupIdentifier:@"YourAppGroupIdentifier"];
NSString *sharedDirectory = [groupContainerURL path];

Then, to write a UIImage (for example) to that folder:

NSData *imageData = UIImagePNGRepresentation(image);
NSString *filePath = [sharedDirectory stringByAppendingPathComponent:@"image.png"];
[imageData writeToFile:filePath atomically:YES];

You can use the same logic in both your Watch extension and iOS app to share files. You can also create your own directories, as there is no "standard" directory structure for shared containers.

like image 140
Mike Swanson Avatar answered Jan 24 '23 12:01

Mike Swanson