iOS:在App Group中保存图像以便在Apple Watch上使用

MSU*_*dog 1 objective-c ios ios-app-group watchkit

背景:

在我的iPhone应用程序中,我检索图像并将其保存到文档目录,以便更快地加载.我知道要在Apple Watch上使用这些图像,我必须与App Group分享.

所以,我创建了一个应用程序组,更新了我的配置文件,所有这些都是爵士乐.现在我的问题是我不知道如何将图像保存到App Group并在WatchKit文件中读取该图像.

以下是我尝试将图像保存到App Group的内容:

NSString *container = @"group.com.appName.watchdatasharing";

NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:container];

[defaults setValue:UIImagePNGRepresentation([FileManager readImageFromFileWithName:@"icon1_imgUrl"]) forKey:@"icon1_imgUrl"];
Run Code Online (Sandbox Code Playgroud)
  • 注意:我的FileManager类返回一个UIImage

要在我的WatchKit应用程序中检索图像,我使用以下代码:

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];
Run Code Online (Sandbox Code Playgroud)

题:

我在Apple Watch上测试时没有显示图像.在申请和Apple Watch之间保存/检索图像时,我需要做些什么?

Kos*_*awa 5

如果您使用watchOS 2,则可以使用WatchConnectivity.我附上一个示例代码供您参考.

在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];
}
Run Code Online (Sandbox Code Playgroud)

观看:

// Receive file from iPhone
- (void)session:(nonnull WCSession *)session didReceiveFile:(nonnull WCSessionFile *)file
{
    // recieve file
}
Run Code Online (Sandbox Code Playgroud)

REF. http://www.kristinathai.com/watchos-2-how-to-communicate-between-devices-using-watch-connectivity/