Background:
In my iPhone app I retrieve images and save them to the documents directory for quicker loading. I know that to use these images on the Apple Watch, I must share them with an App Group.
So, I create an App Group, updated my provisioning profile, all that jazz. Now my problem is that I do not know how to save an image to the App Group and read that image within my WatchKit files.
Here is what I have tried for saving the image to the App Group:
NSString *container = @"group.com.appName.watchdatasharing";
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:container];
[defaults setValue:UIImagePNGRepresentation([FileManager readImageFromFileWithName:@"icon1_imgUrl"]) forKey:@"icon1_imgUrl"];
And to retrieve the image in my WatchKit app, I use this code:
NSString *container = @"group.com.fantrac.watchdatasharing";
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:container];
NSData* imageData = [defaults valueForKey:@"icon1_imgUrl"];
UIImage* image = [UIImage imageWithData:imageData];
[tableRow.iconImage setImage:image];
Question:
There is not image showing when I test on the Apple Watch. What do I need to do differently to save/ retrieve the images between my app and Apple Watch?
If you use watchOS 2, you can use WatchConnectivity. I attach a sample code for your reference.
on iPhone:
// Create a Watch Connectivity session
- (void)viewDidLoad
{
[super viewDidLoad];
self.applicationDict = @{@"foo" : @"bar"};
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
}
}
// Transfer file to Apple Watch
- (IBAction)fileTransferButtonTapped:(id)sender
{
// File Transfer
NSURL *url =
[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sample" ofType:@"png"]];
WCSessionFileTransfer *fileTransfer =
[[WCSession defaultSession] transferFile:url
metadata:self.applicationDict];
}
on Watch:
// Receive file from iPhone
- (void)session:(nonnull WCSession *)session didReceiveFile:(nonnull WCSessionFile *)file
{
// recieve file
}
ref. http://www.kristinathai.com/watchos-2-how-to-communicate-between-devices-using-watch-connectivity/