Using same iCloud enabled CoreData store across Wa

2019-09-07 17:00发布

I'm witnessing some strange behaviour when opening iCloud Enabled CoreData store from Apple Watch Extension. I'm using the same iCloud Container across all targets.

Here is a picture that shows what folder (ubiquity container) structure looks like inside the ubiquity container :

Different stores for Apple Watch & iPhone

It looks like it creates different stores for iPhone & Watch

I'm sharing the same CoreData Stack between iPhone app & Watch Extension. Any ideas why this is happening ? If I understand this correctly it treats iPhone app & Watch Extension as a separate users ?

I would really appreciate if someone could give an advice.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-07 17:20

You should use app groups to share the same Core Data store between Watch and iPhone. Enable app groups for both targets, configure it in your provisioning profiles and then get your persistent store URL like this:

NSURL *storeURL = [[NSFileManager defaultManager] 
     containerURLForSecurityApplicationGroupIdentifier:appGroupIdentifier];

The watch would be accessing the Core Data store via a WatchKit extension also enabled for app groups. See e.g. Figure 4.1 in Apple's App Extension Programming Guide.

enter image description here

查看更多
手持菜刀,她持情操
3楼-- · 2019-09-07 17:33

Consider having your WatchKit Extension use openParentApplication to communicate with the parent app. Using openParentApplication is simple to implement and helps keep the code in the WatchKit extension simple and fast.

From the WatchKit Extension InterfaceController, call openParentApplication.

NSDictionary *requst = @{@"request":@"myRequest"};

    [InterfaceController openParentApplication:requst reply:^(NSDictionary *replyInfo, NSError *error) {

            if (error) {
                NSLog(@"%@", error);
            } else {
                // DO STUFF
            }
        }];

Then, reply from the app using

 - (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply{

Consider also using JSON data (NSJSONSerialization) in the main app to respond to the watch extension.

查看更多
登录 后发表回答